ASP.NET MVC In-Depth: The Life of an ASP.NET MVC Request

The purpose of this blog entry is to describe, in painful detail, each step in the life of an ASP.NET MVC request from birth to death. I want to understand everything that happens when you type a URL in a browser and hit the enter key when requesting a page from an ASP.NET MVC website.

Why do I care? There are two reasons. First, one of the promises of ASP.NET MVC is that it will be a very extensible framework. For example, you’ll be able to plug in different view engines to control how your website content is rendered. You also will be able to manipulate how controllers get generated and assigned to particular requests. I want to walk through the steps involved in an ASP.NET MVC page request because I want to discover any and all of these extensibility points.

Second, I’m interested in Test-Driven Development. In order to write unit tests for controllers, I need to understand all of the controller dependencies. When writing my tests, I need to mock certain objects using a mocking framework such as Typemock Isolator or Rhino Mocks. If I don’t understand the page request lifecycle, I won’t be able to effectively mock it.

Two Warnings

But first, two warnings.

Here's the first warning: I’m writing this blog entry a week after the ASP.NET MVC Preview 2 was publicly released. The ASP.NET MVC framework is still very much in Beta. Therefore, anything that I describe in this blog entry might be outdated and, therefore, wrong in a couple of months. So, if you are reading this blog entry after May 2008, don’t believe everything you read.

Second, this blog entry is not meant as an overview of ASP.NET MVC. I describe the lifecycle of an ASP.NET MVC request in excruciating and difficult to read detail. Okay, you have been warned.

Overview of the Lifecycle Steps

There are five main steps that happen when you make a request from an ASP.NET MVC website:

1. Step 1 – The RouteTable is Created

This first step happens only once when an ASP.NET application first starts. The RouteTable maps URLs to handlers.

2. Step 2 – The UrlRoutingModule Intercepts the Request

This second step happens whenever you make a request. The UrlRoutingModule intercepts every request and creates and executes the right handler.

3. Step 3 – The MvcHandler Executes

The MvcHandler creates a controller, passes the controller a ControllerContext, and executes the controller.

4. Step 4 – The Controller Executes

The controller determines which controller method to execute, builds a list of parameters, and executes the method.

5. Step 5 – The RenderView Method is Called

Typically, a controller method calls RenderView() to render content back to the browser. The Controller.RenderView() method delegates its work to a particular ViewEngine.

Let’s examine each of these steps in detail.

Step 1 : The RouteTable is Created

When you request a page from a normal ASP.NET application, there is a page on disk that corresponds to each page request. For example, if you request a page named SomePage.aspx then there better be a page named SomePage.aspx sitting on your web server. If not, you receive an error.

Technically, an ASP.NET page represents a class. And, not just any class. An ASP.NET page is a handler. In other words, an ASP.NET page implements the IHttpHandler interface and has a ProcessRequest() method that gets called when you request the page. The ProcessRequest() method is responsible for generating the content that gets sent back to the browser.

So, the way that a normal ASP.NET application works is simple and intuitive. You request a page, the page request corresponds to a page on disk, the page executes its ProcessRequest() method and content gets sent back to the browser.

An ASP.NET MVC application does not work like this. When you request a page from an ASP.NET MVC application, there is no page on disk that corresponds to the request. Instead, the request is routed to a special class called a controller. The controller is responsible for generating the content that gets sent back to the browser.

When you write a normal ASP.NET application, you build a bunch of pages. There is always a one-to-one mapping between URLs and pages. Corresponding to each page request, there better be a page.

When you build an ASP.NET MVC application, in contrast, you build a bunch of controllers. The advantage of using controllers is that you can have a many-to-one mapping between URLs and pages. For example, all of the following URLs can be mapped to the same controller:

http://MySite/Products/1

http://MySite/Products/2

http://MySite/Products/3

The single controller mapped to these URLs can display product information for the right product by extracting the product Id from the URL. The controller approach is more flexible than the classic ASP.NET approach. The controller approach also results in more readable and intuitive URLs.

So, how does a particular page request get routed to a particular controller? An ASP.NET MVC application has something called a Route Table. The Route Table maps particular URLs to particular controllers.

An application has one and only one Route Table. This Route Table is setup in the Global.asax file. Listing 1 contains the default Global.asax file that you get when you create a new ASP.NET MVC Web Application project by using Visual Studio.

Listing 1 – Global.asax

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:  using System.Web.Mvc;
   6:  using System.Web.Routing;
   7:   
   8:  namespace TestMVCArch
   9:  {
  10:      public class GlobalApplication : System.Web.HttpApplication
  11:      {
  12:          public static void RegisterRoutes(RouteCollection routes)
  13:          {
  14:              // Note: Change the URL to "{controller}.mvc/{action}/{id}" to enable
  15:              //       automatic support on IIS6 and IIS7 classic mode
  16:   
  17:              routes.Add(new Route("{controller}/{action}/{id}", new MvcRouteHandler())
  18:              {
  19:                  Defaults = new RouteValueDictionary(new { action = "Index", id = "" }),
  20:              });
  21:   
  22:              routes.Add(new Route("Default.aspx", new MvcRouteHandler())
  23:              {
  24:                  Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }),
  25:              });
  26:          }
  27:   
  28:          protected void Application_Start(object sender, EventArgs e)
  29:          {
  30:              RegisterRoutes(RouteTable.Routes);
  31:          }
  32:      }
  33:  }

An application’s Route Table is represented by the static RouteTable.Routes property. This property represents a collection of Route objects. In the Global.asax file in Listing 1, two Route objects are added to the Route Table when the application first starts (The Application_Start() method is called only once when the very first page is requested from a website).

A Route object is responsible for mapping URLs to handlers. In Listing 1, two Route objects are created. Both Route objects map URLs to the MvcRouteHandler. The first Route maps any URL that follows the pattern {controller}/{action}/{id} to the MvcRouteHandler. The second Route maps the particular URL Default.aspx to the MvcRouteHandler.

By the way, this new routing infrastructure can be used independently of an ASP.NET MVC application. The Global.asax file maps URLs to the MvcRouteHandler. However, you have the option of routing URLs to a different type of handler. The routing infrastructure described in this section is contained in a distinct assembly named System.Web.Routing.dll. You can use the routing without using the MVC.

Step 2 : The UrlRoutingModule Intercepts the Request

Whenever you make a request against an ASP.NET MVC application, the request is intercepted by the UrlRoutingModule HTTP Module. An HTTP Module is a special type of class that participates in each and every page request. For example, classic ASP.NET includes a FormsAuthenticationModule HTTP Module that is used to implement page access security using Forms Authentication.

When the UrlRoutingModule intercepts a request, the first thing the module does is to wrap up the current HttpContext in an HttpContextWrapper2 object. The HttpContextWrapper2 class, unlike the normal HttpContext class, derives from the HttpContextBase class. Creating a wrapper for HttpContext makes it easier to mock the class when you are using a Mock Object Framework such as Typemock Isolator or Rhino Mocks.

Next, the module passes the wrapped HttpContext to the RouteTable that was setup in the previous step. The HttpContext includes the URL, form parameters, query string parameters, and cookies associated with the current request. If a match can be made between the current request and one of the Route objects in the Route Table, then a RouteData object is returned.

If the UrlRoutingModule successfully retrieves a RouteData object then the module next creates a RouteContext object that represents the current HttpContext and RouteData. The module then instantiates a new HttpHandler based on the RouteTable and passes the RouteContext to the new handler’s constructor.

In the case of an ASP.NET MVC application, the handler returned from the RouteTable will always be an MvcHandler (The MvcRouteHandler returns an MvcHandler). Whenever the UrlRoutingModule can match the current request against a Route in the Route Table, an MvcHandler is instantiated with the current RouteContext.

The last step that the module performs is setting the MvcHandler as the current HTTP Handler. An ASP.NET application calls the ProcessRequest() method automatically on the current HTTP Handler which leads us to the next step.

Step 3 : The MvcHandler Executes

In the previous step, an MvcHandler that represents a particular RouteContext was set as the current HTTP Handler. An ASP.NET application always fires off a certain series of events including Start, BeginRequest, PostResolveRequestCache, PostMapRequestHandler, PreRequestHandlerExecute, and EndRequest events (there are a lot of application events – for a complete list, lookup the HttpApplication class in the Microsoft Visual Studio 2008 Documentation).

Everything described in the previous section happens during the PostResolveRequestCache and PostMapRequestHandler events. The ProcessRequest() method is called on the current HTTP Handler right after the PreRequestHandlerExecute event.

When ProcessRequest() is called on the MvcHandler object created in the previous section, a new controller is created. The controller is created from a ControllerFactory. This is an extensibility point since you can create your own ControllerFactory. The default ControllerFactory is named, appropriately enough, DefaultControllerFactory.

The RequestContext and the name of the controller are passed to the ControllerFactory.CreateController() method to get a particular controller. Next, a ControllerContext object is constructed from the RequestContext and the controller. Finally, the Execute() method is called on the controller class. The ControllerContext is passed to the Execute() method when the Execute() method is called.

Step 4 : The Controller Executes

The Execute() method starts by creating the TempData object (called the Flash object in the Ruby on Rails world). The TempData can be used to store temporary data that must be used with the very next request (TempData is like Session State with no long-term memory).

Next, the Execute() method builds a list of parameters from the request. These parameters, extracted from the request parameters, will act as method parameters. The parameters will be passed to whatever controller method gets executed.

The Execute() method finds a method of the controller to execute by using reflection on the controller class (.NET reflection and not navel gazing reflection). The controller class is something that you wrote. So the Execute() method finds one of the methods that you wrote for your controller class and executes it. The Execute() method will not execute any controller methods that are decorated with the NonAction attribute.

At this point in the lifecycle, we’ve entered your application code.

Step 5 : The RenderView Method is Called

Normally, your controller methods end with a call to either the RenderView() or RedirectToAction() method. The RenderView() method is responsible for rendering a view (a page) to the browser.

When you call a controller’s RenderView() method, the call is delegated to the current ViewEngine’s RenderView() method. The ViewEngine is another extensibility point. The default ViewEngine is the WebFormViewEngine. However, you can use another ViewEngine such as the NHaml ViewEngine.

The WebFormViewEngine.RenderView() method uses a class named the ViewLocator class to find the view. Next, it uses a BuildManager to create an instance of a ViewPage class from its path. Next, if the page has a master page, the location of the master page is set (again, using the ViewLocator class). If the page has ViewData, the ViewData is set. Finally, the RenderView() method is called on the ViewPage.

The ViewPage class derives from the base System.Web.UI.Page class. This is the same class that is used for pages in classic ASP.NET. The final action that RenderView() method performs is to call ProcessRequest() on the page class. Calling ProcessRequest() generates content from the view in the same way that content is generated from a normal ASP.NET page.

Extensibility Points

The ASP.NET MVC lifecycle was designed to include a number of extensibility points. These are points where you can customize the behavior of the framework by plugging in a custom class or overriding an existing class. Here’s a summary of these extensibility points:

1. Route objects – When you build the Route Table, you call the RouteCollection.Add() method to add new Route objects. The Add() method accepts a RouteBase object. You can implement your own Route objects that inherit from the base RouteBase class.

2. MvcRouteHandler – When building an MVC application, you map URLs to MvcRouteHandler objects. However, you can map a URL to any class that implements the IRouteHandler interface. The constructor for the Route class accepts any object that implements the IRouteHandler interface.

3. MvcRouteHandler.GetHttpHandler() – The GetHttpHandler() method of the MvcRouteHandler class is a virtual method. By default, an MvcRouteHandler returns an MvcHandler. If you prefer, you can return a different handler by overriding the GetHttpHandler() method.

4. ControllerFactory – You can assign a custom class by calling the System.Web.MVC.ControllerBuilder.Current.SetControllerFactory() method to create a custom controller factory. The controller factory is responsible for returning controllers for a given controller name and RequestContext.

5. Controller – You can implement a custom controller by implementing the IController interface. This interface has a single method: Execute(ControllerContext controllerContext).

6. ViewEngine – You can assign a custom ViewEngine to a controller. You assign a ViewEngine to a controller by assigning a ViewEngine to the public Controller.ViewEngine property. A ViewEngine must implement the IViewEngine interface which has a single method: RenderView(ViewContext viewContext).

7. ViewLocator – The ViewLocator maps view names to the actual view files. You can assign a custom ViewLocator to the default WebFormViewEngine.ViewLocator property.

If you can think of any other extensibility points that I overlooked, please add a comment to this blog post and I will update this entry.

Summary

The goal of this blog entry was to describe the entire life of an ASP.NET MVC request from birth to death. I examined the five steps involved in processing an ASP.NET MVC request: Creating the RouteTable, Intercepting the request with the UrlRoutingModule, Generating a Controller, Executing an Action, and Rendering a View. Finally, I talked about the points at which the ASP.NET MVC Framework can be extended.

16 Comments

  • Great stuff Steven...you're saving me a lot of time getting more up-to-speed on this stuff. :-)

  • *sigh* I love MVC, I wish I could use it at work!

  • Thanks for the detail. It's good to know what's going on under the hood.

  • Thanks for this post, this is exactly the kind of info I want before jumping in!

  • Great! MVC life cycle

  • Thanks for the insight.

    I have a question, say I had a html page that had a javascript object on it, and I used a async call to a web service. This web service, using Scott Gu's templating system he blogged about sometime ago, on the server, would create a page, add a usercontrol to it, render the usercontrol, get the html back and pass it back as a response to the calling js. Could that web service, instantiate an instance of the MVC lifecycle on the server instead, rendering a View rather then a user control? I have it working by the web service making a webrequest to the controller/action/ url, but that seems wrong to me, I was pretty keen to just fire it off.

    Any ideas anyone?

  • @Henry,

    Did you see my previous blog post on using AJAX with MVC? Go to: http://weblogs.asp.net/stephenwalther/archive/2008/03/14/using-asp-net-ajax-with-asp-net-mvc.aspx

    You can use the client-side WebRequest object to grab HTML content from the server and you can have a controller action render out a fragment of HTML. For example, you could render out HTML generated from a user control from a controller action. Why do you say that it is wrong to make a "webrequest to the controller/action/ url"? I don't understand what you mean by saying that you just want to "fire it off"? This is a subject that I am really interested in, so please clarify what you mean.

  • @swalther

    Ah, nice blog. Yes that is excatly what I have ended up doing, basically using the client-side WebRequest to get the HTML. What I was doing before however was this:

    Javascript WebService Request
    - WebService (server side Web Request to MVC URL)
    - HTML returned to Webservice and parsed to remove unnecessary html markup (body tag, scrip references etc)
    - parsed HTML returned to called javascript

    The reason I was doing this was that I wanted to only pass needed HTML around, but I wanted the other people developing on the system to be able to use stuff like the ajaxtoolkit and so on. Seemed to work but it also seemed to not be kosher (two server request for everything, the mvc pages would lose the asp.net membership stuff as it was the server making the request, not the client (I guess)) so I have gone to getting the HTML through the WebRequest and parsing the HTML returned on the client side instead.

  • Sometimes, this is the level of detail that you need. Thanks for this.

    I am currently struggling with doing unit tests of code which does authentication using an ActionFilter (based on the Rob Conery blog post). It would be a useful addition to this post if you could detail how ActionFilters fit in to the flow.
    cheers

  • @swalther - just bought your ASP 3.5 Unleashed book - good stuff!

    I'm looking forward to MVC but not ready to dive into it until it is production ready and I can use it on my sites. Are there URL mapping solutions usable in the interim? I want to be able to use urls like /State/City/Topic.aspx and for years have been able to map Topic.aspx to Generic.aspx?view=topic using HTTP modules or handlers but AFAIK there is no easy way to map to folder names in IIS so that /State/City doesn't have to exist. Is there a way? Does anyone know when MVC will be production ready?

    Thanks

  • Many thanks for a great write up on the page life cycle, helped me sort out a presentation :D

  • Is your write-up still correct as of the Beta 1 release?

  • Asp net mvc in depth the life of an asp net mvc request.. Outstanding :)

  • You can certainly see your skills in the work you write.
    The world hopes for even more passionate writers like you who aren't afraid to say how they believe. Always follow your heart.

  • Thanks for finally writing about >ASP.NET
    MVC In-Depth: The Life of an ASP.NET MVC Request - Stephen Walther
    on ASP.NET MVC <Loved it!

  • We're a bunch of volunteers and starting a new scheme in our community. Your site provided us with useful information to work on. You have performed a formidable task and our whole neighborhood shall be thankful to you.

Comments have been disabled for this content.