ASP. NET MVC life cycle

Source: Internet
Author: User
Tags ruby on rails

The purpose of this article is to describe in detail every process that ASP. NET MVC requests from start to finish. I want to understand anything that happens after the browser enters a URL and taps enter to request a page for an ASP. NET MVC site.

Why do you need to care about this? There are two reasons. The first is that ASP. NET MVC is a very extensible framework. For example, we can insert different viewengine to control how the site content is rendered. We can also define how the controller generates and assigns to a request. Because I want to explore any extension points for the ASP. NET MVC page request, I'm going to explore some of the steps in the request process.

Second, if you are interested in test-driven development like Blake, when writing unit tests for a controller, we must understand the controller's dependencies. When writing tests, we need to emulate some objects using mock frames such as Typemock isolator or rhino mocks. If you do not understand the page request life cycle, you cannot perform a valid simulation.

Overview of life cycle steps

When we make a request to the ASP. NET MVC site, there are 5 main steps:

Step 1: Create the RouteTable

The first step occurs when the ASP. NET application starts for the first time. RouteTable maps the URL to handler.

Step 2:urlroutingmodule Intercept Request

The second step occurs when we initiate the request. UrlRoutingModule intercepts each request and creates and executes the appropriate handler.

Step 3: Execute Mvchandler

Mvchandler creates the controller and passes the controller in to ControllerContext, then executes the controller.

Step 4: Execute the Controller

The controller detects the Controller method to be executed, constructs the parameter list, and executes the method.

Step 5: Call the Renderview method

In most cases, the Controller method calls Renderview () to render the content back to the browser. The Controller.renderview () method delegates the work to a viewengine.

Now let's take a look at each step in detail:

Step 1: Create the RouteTable

When we request a normal ASP. NET Application page, there is a page on the disk for each page request. For example, if we request a page called somepage.aspx, there will be a page called somepage.aspx on the Web server. If not, you will get an error.

Technically speaking, ASP. NET page represents a class and is not a normal class. Asp. NET page is a handler. In other words, ASP. NET page implements the IHttpHandler interface and has a ProcessRequest () method to accept requests when the page is requested. The ProcessRequest () method is responsible for generating the content and sending it back to the browser.

As a result, common ASP. NET applications work like Blake simple and straightforward. We request the page, the page request corresponds to a page on the disk, this page executes the ProcessRequest () method and sends the content back to the browser.

The ASP. NET MVC application does not work this way. When we request a page for an ASP. NET MVC application, there is no page on the disk that corresponds to the request. Instead, the request is routed to a class called a controller. The controller is responsible for generating the content and sending it back to the browser.

When we write a normal ASP. NET application, we create a lot of pages. Mapping between URLs and pages always corresponds to one by one. Each page request corresponds to the corresponding page.

Instead, when we create an ASP. NET MVC application, we create a batch of controllers. The advantage of using a controller is that you can have many-to-one mappings 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

These URLs map to a controller and display the correct product by extracting the product ID from the URL. This controller approach is more flexible than the traditional ASP. Controller mode can be a more obvious URL for the product.

So, how is a page request routed to a controller? An ASP. NET MVC application has something called a route table. The routing table maps a URL to a controller.

An application has one and only one routing table. The routing table is created in the Global.asax file. Listing 1 contains the default Global.asax file when you use Visual Studio to create a new ASP. NET MVC Web application.

List 1–global.asax

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

The application's routing table is represented by a static property of Routetable.routes. This property represents a collection of routing objects. In the Global.asax file listed in Listing 1, we added two route objects for the routing table when the application first started (the Application_Start () method was called once for the first time the Web page was requested).

The routing object is responsible for mapping the URL to handler. In Listing 1, we have created two route objects. All 2 objects map URLs to Mvcroutehandler. The first route maps any URLs that conform to the {Controller}/{action}/{id} pattern to Mvcroutehandler. The second route maps a URL default.aspx to Mvcroutehandler.

By the way, this new routing architecture can be used independently from ASP. Global.asax file map URL to Mvcroutehandler. However, we can choose to route URLs to different types of handler. The routing architecture mentioned here is contained in a separate assembly called System.Web.Routing.dll. We can use routing out of MVC.

Step 2:urlroutingmodule Intercept Request

When we initiate a request for an ASP. NET MVC application, the request is intercepted by the UrlRoutingModule HTTP module. The HTTP module is a special type of class that participates in each page request. For example, traditional ASP. NET contains the FormsAuthenticationModule HTTP module used to implement page access security using form validation.

UrlRoutingModule the first thing to do after intercepting a request is to wrap the current HttpContext as a HttpContextWrapper2 object. The HttpContextWrapper2 class differs from the normal HttpContext class derived from HttpContextBase. Creating a HttpContext wrapper makes it easier to simulate mock object frames such as Typemock isolator or rhino mocks.

The module then passes the wrapped HttpContext to the routetable created in the previous step. HttpContext contains the URL, form parameters, query string parameters, and the cookie associated with the current request. If a match is found between the routing objects in the current request and the routing table, the routing object is returned.

If UrlRoutingModule successfully acquires the Routedata object, the module then creates a Routecontext object that represents the current HttpContext and Routedata. Module then instantiates a new httphandler based on RouteTable and passes Routecontext to the handler constructor.

For an ASP. NET MVC application, the handler returned from RouteTable is always Mvchandler (Mvcroutehandler returns Mvchandler). As long as the UrlRoutingModule matches the current request to the route in the routing table, the Mvchandler with the current routecontext is instantiated.

The final step of the module is to set the Mvchandler to the current HTPP Handler. Asp. NET application automatically invokes the ProcessRequest () method of the current HTTP handler and then moves on to the next step.

Step 3: Execute Mvchandler

In the previous steps, the Mvchandler that represents a routecontext is set as the current HTTP Handler. Asp. NET application will always initiate a series of events, including star, BeginRequest, Postresolverequestcache, Postmaprequesthandler, PreRequestHandlerExecute and EndRequest events (very many application events-for a complete list, refer to the HttpApplication class in the visual Studio 2008 documentation).

Everything described in the previous content occurs in Postresolverequestcache and Postmaprequesthandler. The ProcessRequest () method of the current HTTP handler is called after the PreRequestHandlerExecute event.

A new controller is created when the ProcessRequest () of the Mvchandler object created in the previous content is called. The controller is created by Controllerfactory. Since we can create our own controllerfactory, this is another extensibility point. The default controllerfactory name is quite appropriate, called defaultcontrollerfactory.

The name of the RequestContext and controller is passed into the Controllerfactory.createcontroller () method to obtain a controller. The ControllerContext object is then constructed from the RequestContext and the controller. Finally, call the Execute () method of the Controller class. The method is passed to the ControllerContext when the Execute () method is called.

Step 4: Execute the Controller

The Execute () method first creates a TempData object (called a Flash object in Ruby on Rails). TempData can be used to save temporary data that must be required for the next request (TempData and session state are similar and do not occupy memory for a long time).

The Execute () method then constructs the parameter list for the request. These parameters are extracted from the request parameters and will be used as arguments to the method. Parameters are passed into the controller method that is executed.

Execute () finds a method of the controller by reflecting on the controller class. The controller class was written by us. The Execute () method executes when it finds a method in our controller class. The Execute () method does not perform the method that is decorated with the nonaction attribute.

At this point, you enter the code for your application.

Step 5: Call the Renderview method

In general, our controller method eventually calls the Renderview () or Redirecttoaction () method. The Renderview () method is responsible for rendering the view (page) to the browser.

When we call the Controller Renderview () method, the call is delegated to the current Viewengine Renderview () method. Viewengine is another extension point. The default viewengine is Webformviewengine. However, we can use other viewengine such as Nhaml.

WebForm's Viewengine.renderview () method creates a class called Viewlocator to find the view. It then uses BuildManager to create an instance of the ViewPage class. Then, if the page has ViewData, the ViewData is set. Finally, ViewPage's Renderview () method is called.

The ViewPage class derives from the System.Web.UI.Page base class (as well as the page used for traditional ASP). The last work done by the Renderview () method is to invoke the ProcessRequest () of the page class. The ProcessRequest () that invokes the view generates content in the same way that ordinary ASP. NET pages generate content.

Extensibility Points

The ASP. NET MVC life cycle is designed with many extensibility points. We can customize the behavior by inserting custom classes or overriding existing classes to customize the framework. The following is a summary of these extension points:

Routing Object : When we create the routing table, call the Routecollection.add () method to add a new routing object. The ADD () method accepts the RouteBase object. We can implement our own routing object by deriving the RouteBase base class.

Mvcroutehandler : When creating an MVC application, we map the URL to the Mvcroutehandler object. However, we can map URLs to any class that implements the Iroutehandler interface. The constructor of the routing class accepts any object that implements the Iroutehandler interface.

Mvcroutehandler.gethttphandler () : The Gethttphandler () method of the Mvcroutehandler class is the virtual method. By default, Mvcroutehandler returns Mvchandler. If you want, we can override the Gethttphandler () method to return different handler.

controllerfactory : We can pass System.Web.MVC.ControllerBuilder.Current.SetControllerFactory () METHOD specifies a custom class to create a custom controller factory. The Controller factory is responsible for returning the controller for a controller name and RequestContext.

Controller : We can implement the custom controller by implementing the IController interface. This interface has only one execute (ControllerContext controllercontext) method.

viewengine: We can specify the custom viewengine for the controller. Assign the Viewengine to the controller by specifying Viewengine for the public Controller.viewengine property. Viewengine must implement the Iviewengine interface with only one method: Renderview (ViewContext viewcontext).

viewlocator : Viewlocator maps The view name to the actual view file. We can perform custom viewlocator through the properties of the Webformviewengine.viewlocator.

ASP. NET MVC life cycle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.