MVC Series (9) How MVC takes over the requested pipeline in the

Source: Internet
Author: User

As we mentioned in the last chapter, the way to dynamically add route before httpmodules initialization comes from defining your own HttpHandler and eventually taking over the request, and that's how MVC works? In this section we will analyze the relevant MVC source code to verify our problem.

First create a MVC3 Web application, select the default template so that after creation, the default includes HomeController and AccountController. We know that MVC takes over the request before it can be handled by these controller. So let's go to the Global.asax.cs file to see the code (to define the takeover request before initializing HttpModule, so you can only come here to find the code (or dynamically add it by using features such as Webactivator), Global.asax.cs the code is very small, but there is something we need , first find a line of code in the Application_Start method:

RegisterRoutes (routetable.routes);

This line of code, see the calling method name RegisterRoutes is registered route meaning, but why the parameter is the global routetable.routes collection? Find the RegisterRoutes method to see the specific content:

public static void RegisterRoutes (RouteCollection routes)  
{  
    routes. Ignoreroute ("{resource}.axd/{*pathinfo}");  
      
    Routes. Maproute (  
        "Default",//Route name  
        "{controller}/{action}/{id}",//URL with parameters  
        New {controller = "H ome ", action =" Index ", id = urlparameter.optional}//Parameter defaults  
    );  
}

The method has 2 lines of code, the first line is to ignore a route (we do not look at this), the second line is to use the Maproute method to register a new route, the default is to map to the Home Controller index action, we may have thought, The Maproute method of RouteCollection (that is, the routetable.routes that was just passed in) is to provide what we call the entrance to the takeover request, but how do you pass the HttpHandler of MVC into it? We went to this maproute method (need to install Reshaper to find MVC's source code), adjusted to the MVC Routecollectionextensions class, Discover that Maproute is not a routecollection method, but an extension method provided in the MVC source code as follows:

public static Route Maproute (this routecollection routes, string name, string URL, object defaults, object constraints, St Ring[] namespaces  
{  
    if (routes = = null)  
    {  
        throw new ArgumentNullException ("routes");  
    }  
    if (url = = null)  
    {  
        throw new ArgumentNullException ("url");  
    }  
      
    Route Route = new Route (URL, new Mvcroutehandler ())  
    {  
        Defaults = new RouteValueDictionary (Defaults),  
        Constraints = new RouteValueDictionary (Constraints),  
        datatokens = new RouteValueDictionary ()  
    };  
      
    if (namespaces!= null) && (namespaces. Length > 0))  
    {  
        route. Datatokens["namespaces"] = namespaces;  
    }  
      
    Routes. ADD (name, route);  
      
    return route;  
}

The main function of the code is to new route, and then add the route to the static set routetable.routes we just mentioned, so that we can use it later to find handler, OK, this step is in line with the analysis in the previous chapters.

Next, how the route is new, the parameters passed in the code are the URLs we know, and a Mvcroutehandler instance, and this step is also consistent with our previous analysis, So let's take a look at how Mvcroutehandler's Gethttphandler method is implemented to get Mvchandler:

public class Mvcroutehandler:iroutehandler {private Icontrollerfactory _controllerfactory; Public Mvcroutehandler () {} public Mvcroutehandler (Icontrollerfactory controllerfactory) {_  
    Controllerfactory = controllerfactory; } protected Virtual IHttpHandler Gethttphandler (RequestContext requestcontext) {requestcontext.http   
        Context.setsessionstatebehavior (Getsessionstatebehavior (RequestContext));   
    return new Mvchandler (RequestContext); } protected Virtual Sessionstatebehavior Getsessionstatebehavior (RequestContext requestcontext) {St  
        Ring Controllername = (string) requestcontext.routedata.values["Controller"]; Icontrollerfactory controllerfactory = _controllerfactory??  
        ControllerBuilder.Current.GetControllerFactory ();   
    Return Controllerfactory.getcontrollersessionbehavior (RequestContext, controllername); } #region Iroutehandler MemberS IHttpHandler iroutehandler.gethttphandler (RequestContext requestcontext) {return Gethttphandler (reques   
    Tcontext); } #endregion}

Looking at the above bold code, Mvcroutehandler implements the Iroutehandler Gethttphandler, which invokes the Gethttphandler virtual method defined by Mvcroutehandler itself, And in this virtual method we see a very important and long-awaited code--Return to the Mvchandler instance, probably look at the class of Mvchandler, get it is what we suspect: A class that inherits from the IHttpHandler interface, and inherits the IHttpAsyncHandler interface, we first regardless of how the Mvchandler interior is implemented, but our previous chapters of the entire analysis has finally been validated, it is said that the MVC has been dedicated to deal with Handler, It then calls its BeginProcessRequest method into the pipeline of MVC itself for processing.

At this point, we finally understand how MVC in the entire ASP.net runtime is how to take over the request, it should be probably clear the entire asp.net runtime operating mechanism, as for the mvchandler implementation of the way, We will be in a lot of chapters later to analyze each line of code, today we have a small task, that is: read the implementation of the MVC mechanism, we can write a custom HttpHandler through route dynamic registration, to achieve our own custom extension, Let's try to do it.

This column more highlights: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/aspx/

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.