[RESOLVED]Read cshtml File with dynamic content into a string


I’m programming a class for Sending Emails out of my Web Application.

Im using the MailMessage class and the SmtpClient.

My Intention is to send an html-mail with dynamic Content. Before I’ve created my dynamic Content for the html-Body in a string variable like so:

string Body = "<html><head></head><Body>Hello, this is {0}...</Body></html>";
string newBody = String.Format(Body, "Content from my Database");

I think this is a Little bit complicated to create my mail Body for the MailMessage.

Now I’ve tried to have my MailBody read from an predesigned cshtml-file via streamReader.

This works fine unless I’m using non dynamic Content because I can adress the file via Server.Mappath(…something.cshtml).

Now I want to have my cshtml-file served by the webserver with dynamic Content and this written into a string like:


So the File has to be rendered by the webserver and then read out?

Ho do I manage this and is it just possible to do this?

For a better understanding my Application should send an Email with the Contents of a guestbook, if a new entry was made.

Thanks for your help.


There’s no reason why you can’t do what you propose. What you need is the rendered output rather than the content of the file itself, so you can use the WebClient class to request the page and obtain the response:

message.Body = new WebClient().DownloadString(string.Format("http://domain.com/something.cshtml?id={0}", YourIdValue));
message.IsBodyHtml = true;

Hello Mike,

thanks for your reply. that’s exactly what I was looking for.

Now it works. Laughing

But there’s still one question.

Is there a method to get the current Domain? I’d like to have my URL dynamic because Webmatrix uses as adress in the browser:


When I upload the file the URL changes of course Request.Url delivers the hole URL.

Thanks in advance


Yes, there is. It’s used in the Starter Site (ForgotPassword.cshtml): Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)

string.Format("{0}/something.cshtml?id={1}", Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped), yourId);

Perfect that’s it.

Thank you very much, Mike.

Best regards, monsee

Leave a Reply