Asp. NET Routing model parsing

Source: Internet
Author: User

All right, I'm going to blow it again.

~-_-~

Reprint please indicate the source: from the blow of the "ASP." NET routing Model Resolution "

Background: Many people know how to use the ASP, but do not know the operating principle of the internal routing model, today I will give you the way to blow down the route module of ASP.

PS: This is for the asp.net4.5 version, as if the latest version of the 5.0 added Owin, completely decoupled and Web server coupling, I have not studied, do not dare to 4.5 of the model for 5.0. (is not my rigorous attitude to deter _-_)

action*0x1: Big Talk ASP.

First of all, we first understand the fate of the next request , and look at the winding road that it has traversed throughout its life. As shown in the following:

(here thanks to the teacher Mullen, the explanation of the spit, finally let me understand its life.) )

In the picture of the beautiful scenery as shown above, we can see a "request" from the client browser, go through the mountains and rivers to reach the server, HTTP. sys of the server's kernel module gave it a warm welcome, and after it was simply modified, it parting with it, because Htpp.sys knew it was a dream "request", it should go where it should go, and sent it to IIS.

IIS is a piece of magical land, There is a great spirit called Inetinfo.exe, so it goes to the place of the gods. W3SVC service (Windows Service) praying, hoping to give him some instructions, the gods by looking through the heavenly book (IIS configuration file), know that it is not a general static file, can not send it directly back, should let it go to its people to run The processing plant (ie, the corresponding site of the work process) to learn a good practice.

The current processing plant boss called W3wp.exe, before IIS6 is aspnet_wp.exe, because there is no management of the site between the processing plant problems were dismissed (asp.net_ Wp.exe with a process to host all the site, with the application domain segmentation, resulting in the interaction between the site, the current boss w3wp.exe through a website a process way to solve the problem, so smooth upper.

First into the processing plant "request" visited the doorman Asp.net_isapi.dll, the doorman found it was the first to come over the "request", so that it opened the factory production workshop (that is, the first request arrived, launched the ASP. NET running environment, later requests can enter the environment directly.) ), and asked the Workshop director Isapiruntime to take charge of it, the Director delighted to welcome it (i.e. Isapiruntime calls the ProcessRequest (PR) method to access the ECB handle where the current request is located), And let rustic it into a unified clothing httpworkrequest (that is, the request for a simple package), and then called the Monitor httpruntime, let the monitor arrange its work.

The monitor said: "There is danger in the workshop, you first put on the safety uniform HttpContext." "(that is, through the PR method to httpworkrequest encapsulation into HttpContext), and then go to the group leader Dormitory (HttpApplicationFactory) ready to call a leader (HttpApplication) to lead it, the results found that no team leader , the monitor had to recruit a new leader.

Each team leader is after rigorous training to post, first to be familiar with the factory guidelines global.asax (that is, compile Global.asax files), and then through the guidelines Application_Start method Test (that is, call Application_Start method), Such a party is a generation leader. The first thing for each new leader is to assemble all the workshop modules and create a good workshop pipeline (by reading the configuration file, loading all the IHttpModule, and calling their Init method, the General Init method is to register the pipeline event, and then through the Buidstepmanager method , the corresponding Stepmanager is generated according to the Classic mode or Integrated mode).

The new leader sees "request", apart directly starts the workshop pipeline, throws it in. Wearing a safety uniform, HttpContext's "request." To go through all the levels in the pipeline (the ASP. NET pipeline model), where after the 7th level, an object of type IHttpHandler is generated and the ProcessRequest method of the object is executed after the 11th level to process the request, where "request" Get the perfect processing molding, generate the HttpResponse, and then through the rest of the pipeline, realize the dream of the request to go along the original road back. Between the 11th and 12 events, the WebForm Page object is described as the process of processing the request (that is, the pages life cycle).

At this point, a request for the ups and downs of life is finished, you want to know how the route module specifically how to play a role, but also please hold a personal field, the bottom right corner of a praise .

ACTION*0X2: Routing Model Resolution

By the above we know that the leader HttpApplication object will be responsible for assembling all the IHttpModule, how is it loaded? We observe the anti-compilation code:

Private void Initmodules () {    = runtimeconfig.getappconfig (). Httpmodules.createmodules ();      This . Createdynamicmodules ();    Modules. Appendcollection (other);     this. _modulecollection = modules;      This . Initmodulescommon ();}

Runtieconfig.getappconfig (). Httpmodules.createmodules (); Through this line of code, we can clearly see that it reads the runtime configuration file, then we open the runtime configuration file to view.

Sure enough, add a system.webrouting here. The urlroutingmodule type. Next we will use the Anti-compilation tool to see this type of source code:

As we expected UrlRoutingModule to implement the IHttpModule interface, let's see what it did with the Init method.

protected Virtual void Init (HttpApplication application) {    ifnull)    {        = _contextkey ;         New EventHandler (this. Onapplicationpostresolverequestcache);}    }

For the 7th Event Postresolverequestcache registration method Onapplicationpostresolverequestcache, then what is this method doing?

 Public Virtual voidPostresolverequestcache (httpcontextbase context) {Routedata Routedata= This. Routecollection.getroutedata (context);//match the route and get the matching result routedata.     if(Routedata! =NULL) {Iroutehandler Routehandler=Routedata.routehandler; if(Routehandler = =NULL)        {            Throw NewInvalidOperationException (string. Format (CultureInfo.CurrentCulture, SR. GetString ("Urlroutingmodule_noroutehandler"),New Object[0])); }        if(! (Routehandler isStoproutinghandler)) {RequestContext RequestContext=NewRequestContext (context, routedata); Context. Request.requestcontext=RequestContext; IHttpHandler HttpHandler= Routehandler.gethttphandler (RequestContext);//gets the IHttpHandler object that handles the current request.             if(HttpHandler = =NULL)            {                Object[] args =New Object[] {routehandler.gettype ()}; Throw NewInvalidOperationException (string. Format (CultureInfo.CurrentUICulture, SR. GetString ("Urlroutingmodule_nohttphandler"), args); }            if(HttpHandler isUrlauthfailurehandler) {                if(!formsauthenticationmodule.formsauthrequired) {Throw NewHttpException (0x191, SR. GetString ("Assess_denied_description3")); } urlauthorizationmodule.reporturlauthorizationfailure (HttpContext.Current, This); }            Else{context. Remaphandler (HttpHandler);//Map: Processes the request with the current IHttpHandler object.             }        }    }}

The code has been annotated, 3 steps: match route → Gets the IHttpHandler object that handles the current request → Mapping: Processes the request with the current IHttpHandler object. The PR method of the IHttpHandler object is then called between the 11th and 12 events to process the current request.

We then tidy up the idea: ASP. NET first registered the UrlRoutingModule module, he is an implementation of the IHttpModule interface class, its Init method is to register a method on the 7th event, the method first matches the route, if the match is successful, then use the matching result routedata I The HttpHandler object is mapped to the current context so that the IHttpHandler object processing request is called between the 11th and 12 events.

So the question is, when is the route object injected, and who is the IHttpHandler object?

Remember how the routing rules were added? As shown in the following code:

 Public classGlobal:System.Web.HttpApplication {protected voidApplication_Start (Objectsender, EventArgs e) {            varDefaults =Newroutevaluedictionary (); Defaults. ADD ("name","*"); //Way One://add an object of route type with routetable static object routes. ROUTETABLE.ROUTES.ADD ("app",NewRoute ("App/{name}", defaults,NewMyroutehandler ())); //Way Two://A new routing rule is added through the RouteTable static object routes extension method. RouteTable.Routes.MapPageRoute ("default","App/{name}","~/webform1.aspx",false, defaults); }    }

This is the two ways we often use to add routing rules, the way one has our own Myroutehandler type of instance as a parameter, in fact, through the Iroutehandler interface to return a IHttpHandler object.

/// <summary>    /// implements the type    of the Iroutehandler interface /// </summary>    Internal class Myroutehandler:iroutehandler    {        public  IHttpHandler gethttphandler (requestcontext requestcontext)        {             // returns a Page object that is used to process the request.             returnnew  WebForm1 ();        }    }

In fact, there is no intrinsic difference between the two ways, because the way two routes are instantiated by the rule parameters of a route object.

The source code of our analysis mode two:

 PublicRoute Mappageroute (stringRouteName,stringROUTEURL,stringPhysicalFile,BOOLcheckphysicalurlaccess, routevaluedictionary defaults, routevaluedictionary constraints, RouteValueDictionary Datatokens) {if(RouteUrl = =NULL)    {        Throw NewArgumentNullException ("ROUTEURL"); } Route Item=NewRoute (ROUTEURL, defaults, constraints, Datatokens,NewPageroutehandler (PhysicalFile, checkphysicalurlaccess));  This.    ADD (RouteName, item); returnitem;}

All routing rule parameters are found to instantiate a route object, where the parameters PhysicalFile and checkphysicalurlaccess are used to instantiate the Pageroutehandler object, the source code is as follows:

 Public class pageroutehandler:iroutehandler{}

This is a implementation of the Iroutehandler interface type, and this interface only one function is to return the IHttpHandler object, the source code is as follows:

[Typeforwardedfrom ("System.Web.Routing, version=3.5.0.0, Culture=neutral, publickeytoken= 31bf3856ad364e35")]publicinterface  iroutehandler{    / /  Methods    ihttphandler gethttphandler (RequestContext requestcontext);}

Here our doubts are solved, originally our registered routing rules are instantiated into the route object, route of the Getroutedata method used to match the route (refer to the blog Park Great God Artech Books), PhysicalFile and checkphysicalurlaccess in routing rules are used to instantiate a IHttpHandler instance to handle the request.

Summary: The routing model for ASP.

Ka

Perfect, knock it off.

SOURCE Download: Poke here

Reprint please indicate the source: from the blow of the "ASP." NET routing Model Resolution "

Asp. NET Routing model parsing

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.