In-process ASP.NET MVC Web Form View Rendering

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 NHaml 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);
 
    HttpRuntime.ProcessRequest(simpleWorkerRequest);
  }
}

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)
      ApplicationHost.CreateApplicationHost(
        typeof(TestApplicationHost),
        "/", 
        @"C:\Dev\MyMvcApplication");
 
    using (var output = new StringWriter())
    {
      applicationHost.ProcessRequest("Account/Login", null, output);
 
      Console.WriteLine(output);
    }
 
    Console.ReadKey();
  }
}

Surprisingly easy actually.

Leave a Reply

Your email address will not be published. Required fields are marked *