-->

ASP.NET (MVC) - render page to a file

2019-04-14 16:12发布

问题:

I have to create a bunch of static html files as console / winform job. The current solution uses a string builder. Having used ASP.NET-MVC with strongly typed view pages (System.Web.Mvc.ViewPage) I was wondering if it is possible to leverage these view pages and have them output to a stream or file without building an ASP.NET solution.

Essentially I'd like to create the viewpage, pass in the strongly typed object, and render the result.

I'm also open to other view engines.

If this ends up requiring bringing over the whole kitchen sink, then I can just do a string builder style.

Thanks.

回答1:

What you need is a templating engine. I would recommend you StringTemplate. It can be used as standalone engine and it has a .NET version. There's a CodeProject article that could get you started.

AFAIK ASP.NET WebForms cannot run without the ASP.NET infrastructure.



回答2:

Note sure if this helps as I was unclear about your question.

[ControllerAction]
public void About()
{
    StringWriter builder = new StringWriter();
    TextWriter originalWriter = Response.Output;
    Response.SwitchWriter(builder);
    RenderView("About");

    string html = builder.ToString();

    originalWriter.Write(html);
}


回答3:

I personally like the StringTemplate option mentioned above, but you can actually host the ASP.NET runtime in a desktop application.

Rick Strahl over at West Wind Technologies has a detailed example of how to set it up: Using the ASP.Net Runtime for extending desktop applications with dynamic HTML Scripts

Here are a couple of other examples:

  • Code Project: Using ASP.NET Runtime in Desktop Applications
  • MSDN Magazine: ASP. NET Client-side Hosting with Cassini -- The nuts and bolts of how to use the ApplicationHost class.
  • Andrew Peter's Blog: In-process ASP.NET MVC Web Form View Rendering