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

雖然這是一篇舊的文章,但確能了解 ASP.NET MVC 它的 Life Cycle 為何?

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.

 

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

留言

  1. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.
    data recovery seattle

    回覆刪除

張貼留言

這個網誌中的熱門文章

WPF - 深入 Style

C# – M$ Chart Control 自定 ToolTip 的顯示

Vue.js - 基礎介紹教學