简体   繁体   中英

How can I use asp.net to generate and return an HTML document as a string (outside of a web context)

I need to write a system to generate HTML email from a data model -

I was going to create a templating system to build the model into an HTML representation using HTML 'fragments' stored in an xml template. But it occurs to me that these it might be better to use asp or asp.net than write my own templating system?

What I am wondering is whether/how it would be possible to use asp (maybe asp.net mvc?) to return an HTML string - I wouldn't be running on a web server, or in response to an HTTP request.

I have not done any asp or asp.net yet- My experience of ASP stretches to 'Create new project' in visual studio - but maybe now is a good time to learn!

Thank You!

The simplest way is to make an aspx page that renders the email and then read it on the server using WebClient or and HttpWebRequest.

System.Net.WebClient oClient = new System.Net.WebClient();
string Email = oClient.DownloadString(UrlOfPage);

There are other ways to capture the output and I am sure if you search on Google you can find articles about this, but from personal experience this is the simplest way to go.

Also beware of the Html/Css limitations of many email clients. It is not the same as a browser.

The standard ASP.NET view engine--ASP.NET web forms--is very difficult to use in this way as it is pretty tied to the HttpContext and really don't want to give you a string back but rather stream into the HttpResponse. So you'd generally need IIS stood up to get it to go.

Xslt (as you are thinking) is a pretty decent option. As is, if things are simple enough, your own template replacement scheme. Now, if things are complex enough, some other options would include:

Either of those should let you get a string out of a template without too much trouble.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM