In-process ASP.NET MVC Web Form View Rendering

Posted by Andrew on November 19, 2008

Sometimes it’s useful to be able to render a view in-process, for example, from within a unit test if you would like to validate the rendered XHTML. View engines like make this easy because they aren’t tightly coupled to the System.Web.* ASP.NET runtime. Web Forms, however, is another story. You cannot simply new up a WebFormViewEngine, nestle it in some moqs and start rendering away merrily. You will quickly run into various exceptions because the ASP.NET runtime has not been properly initialized.

All is not lost however. Here’s how you can easily render Web Forms views using the ASP.NET Hosting API:

First, create an Application Host class. Inherit MarshalByRefObject because this will run ASP.NET in a separate App Domain. Add a method, ProcessRequest, that will request a view through the runtime.

public sealed class TestApplicationHost : MarshalByRefObject
  public void ProcessRequest(string page, string query, TextWriter output)
    var simpleWorkerRequest 
      = new SimpleWorkerRequest(page, query, output);

Second, create your host which points to an ASP.NET app and render a view.

public sealed class Program
  private static void Main()
    var applicationHost = (TestApplicationHost)
    using (var output = new StringWriter())
      applicationHost.ProcessRequest("Account/Login", null, output);

Surprisingly easy actually.


Use this link to trackback from your own site.


Leave a response

  1. Wed, 19 Nov 2008 19:20:15 CST

    In-process ASP.NET MVC Web Form View Rendering…

    You’ve been kicked (a good thing) - Trackback from…

  2. Mon, 15 Jun 2009 11:02:16 CDT


    how did you overcome the issue that the actual assembly with TestApplicationHost needs to be available for the ASP.NET runtime? Do you have some sort of hack to do that or did you simply copy it to the bin folder?


  3. AndrewNo Gravatar Fri, 03 Jul 2009 15:54:32 CDT

    Just copied it :-)