Analysis of the working principle of ASP. NET routing model, analysis of asp.net

Source: Internet
Author: User

Analysis of the working principle of ASP. NET routing model, analysis of asp.net

Ps: This is for ASP. in NET4.5, it seems that the OWIN has been added to the latest version 5.0, which completely decouples the coupling with the Web server. I have not studied it yet and dare not say that the 4.5 model applies to 5.0.

Action * 0x1: ASP. NET Model

First, let's take a look at the joys and sorrows of the next request and the twists and turns it has taken in its life. As shown in:

As shown in the above figure, we can see a "request" starting from the client browser, which goes through the HTTP of the kernel module of the server. SYS warmly treats it. After simple modification, it will be different from it because HTTP. SYS knows that it is a "request" with a dream. It should go where it should go, so it is sent to IIS.

Iisis an amazing land. Here there is a great spirit called inetinfo.exe, so it went to the god's home W3SVC Service (windows Service) to pray, hoping to give him some instructions, the god by checking the tianshu (IIS configuration file ), knowing that it is not a common static file, you cannot send it back directly. You should let it go to the processing factory run by its people (that is, in the working process of the corresponding website) to study it well.

The hacker solved the problem through a process on the website, so it went smoothly to the upper level.

The "request" from the initial import factory visited the guard asp.net _ isapi. dll, the guard found that it was the first "request", so it opened the factory production workshop for it (that is, when the first request arrived, it started the asp.net runtime environment, later requests can directly enter this environment .), Ask the workshop director ISAPIRuntime to take charge of it. The director happily welcomes it (that is, ISAPIRuntime calls the ProcessRequest (PR) method to access the ecb handle of the current request ), and let it replace with the uniform clothing HttpWorkRequest (that is, to encapsulate the request in a simple way), and then call the shift leader HttpRuntime to let the shift leader arrange its work.

The shift leader said, "There is a danger in the workshop. You should first wear a security uniform HttpContext ." (That is, encapsulate HttpWorkRequest into HttpContext through the PR method), and then go to the group leader dormitory (HttpApplicationFactory) to prepare a group leader (HttpApplication) to lead it. The result shows that no team leader exists, the class leader had to recruit a new team leader.

Every team lead is trained to take up their posts. First, they must read the factory standards Global. asax (that is, compile Global first. asax file), and then pass the Application_Start method test in the criterion (that is, call the Application_Start method), so as to become a generation leader. The first thing for each new leader is to assemble all the workshop modules and create a workshop pipeline (by reading the configuration file, loading all the ihttpmodules, and calling their Init method, generally, the init method registers MPs queue events, and then generates corresponding StepManager based on the classic mode or integrated mode through the BuidStepManager method ).

When the new team leader sees the request, he will directly start the workshop pipeline and drop it in. Requests for HttpContext in a security uniform are sequentially passed through all the levels in the pipeline (asp.net pipeline model). After 7th levels, IHttpHandler type objects are generated, and after 11th levels, execute the ProcessRequest method of the object to process the request. Here, the "request" is perfectly crafted, and the HttpResponse is generated, and then the remaining pipeline is used, the request for realizing the dream will be returned along the original path. Between 11th and 12 events, the Page object of WebForm processes the request (that is, the Page lifecycle ).

At this point, the ups and downs of a request are all over. To learn how the routing module works, please hold your personal website and click "like" in the lower right corner.

Action * 0x2: route model resolution

Through the above, we know that the team lead HttpApplication object will be responsible for assembling all the ihttpmodules. How does it load it? Observe the decompiled code:

private void InitModules(){HttpModuleCollection modules = RuntimeConfig.GetAppConfig().HttpModules.CreateModules();HttpModuleCollection other = this.CreateDynamicModules();modules.AppendCollection(other);this._moduleCollection = modules;this.InitModulesCommon();}

RuntimeConfig. getAppConfig (). httpModules. createModules (); through this line of code, we can clearly find that it has read the configuration file during the runtime, so we can open the configuration file during the runtime to see the actual situation.


A System. WebRouting. UrlRoutingModule type is added here. Next we will use the decompilation tool to view the source code of this type:

As expected, UrlRoutingModule implements the IHttpModule interface. Let's see what the Init method does?

protected virtual void Init(HttpApplication application){if (application.Context.Items[_contextKey] == null){application.Context.Items[_contextKey] = _contextKey;application.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache);}}

For the registration method OnApplicationPostResolveRequestCache for 7th events, what does this method do?

Public virtual void PostResolveRequestCache (HttpContextBase context) {RouteData routeData = this. RouteCollection. GetRouteData (context); // match the route to obtain the matching result RouteData. If (routeData! = Null) {IRouteHandler routeHandler = routeData. routeHandler; if (routeHandler = null) {throw new InvalidOperationException (string. format (CultureInfo. currentCulture, SR. getString ("UrlRoutingModule_NoRouteHandler"), new object [0]);} if (! (RouteHandler is StopRoutingHandler) {RequestContext requestContext = new RequestContext (context, routeData); context. request. requestContext = requestContext; IHttpHandler httpHandler = routeHandler. getHttpHandler (requestContext); // gets the IHttpHandler object that processes the current request. If (httpHandler = null) {object [] args = new object [] {routeHandler. getType ()}; throw new InvalidOperationException (string. format (CultureInfo. currentUICulture, SR. getString ("UrlRoutingModule_NoHttpHandler"), args);} if (httpHandler is UrlAuthFailureHandler) {if (! FormsAuthenticationModule. formsAuthRequired) {throw new HttpException (0x191, SR. getString ("Assess_Denied_Description3");} UrlAuthorizationModule. reportUrlAuthorizationFailure (HttpContext. current, this);} else {context. remapHandler (httpHandler); // ing: process the request with the current IHttpHandler object .}}}}

The Code has been annotated. Step 3: match the route → get the IHttpHandler object that processes the current request → ing: process the request with the current IHttpHandler object. The IHttpHandler object's PR method will be called between 11th and 12 events to process the current request.

Let's sort out the following ideas: ASP. NET first registers the UrlRoutingModule module, which is a class that implements the IHttpModule interface. Its Init method is to register a method on 7th events. This method first matches the route, if the match succeeds, the IHttpHandler object in the matched RouteData will be mapped to the current context. In this way, the IHttpHandler object will be called between the last 11th and 12 events to process the request.

So the question is, when is the Route object injected? Who is the IHttpHandler object?

Do you still remember how the routing rules were added? As shown in the following code:

Public class Global: System. web. httpApplication {protected void Application_Start (object sender, EventArgs e) {var defaults = new RouteValueDictionary (); defaults. add ("name", "*"); // Method 1: // Add a Route-type object through the RouteTable static object Routes. RouteTable. routes. add ("app", new Route ("app/{name}", defaults, new MyRouteHandler (); // Method 2: // Add a routing rule through the Routes Extension Method of the static object of RouteTable. RouteTable. Routes. MapPageRoute ("default", "app/{name }","~ /WebForm1.aspx ", false, defaults );}}

This is often used to add routing rules in two ways. In method 1, there is a MyRouteHandler instance compiled by ourselves as a parameter. In fact, an IHttpHandler object is returned through the IRouteHandler interface.

/// <Summary> /// implement the IRouteHandler interface type // </summary> internal class MyRouteHandler: IRouteHandler {public IHttpHandler GetHttpHandler (RequestContext requestContext) {// return a Page Object for processing requests. Return new WebForm1 ();}}

In fact, there is no essential difference between the two methods, because the routing rule parameters in method 2 will instantiate a Route object.

Source code of Method 2:

public Route MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens){if (routeUrl == null){throw new ArgumentNullException("routeUrl");}Route item = new Route(routeUrl, defaults, constraints, dataTokens, new PageRouteHandler(physicalFile, checkPhysicalUrlAccess));this.Add(routeName, item);return item;} 

All routing rule parameters are used to instantiate a Route object. The physicalFile and checkPhysicalUrlAccess parameters are used to instantiate the PageRouteHandler object. The source code is as follows:

public class PageRouteHandler : IRouteHandler{} 

This is a type that implements the IRouteHandler interface, and this interface has only one function to return the IHttpHandler object. The source code is as follows:

[TypeForwardedFrom("System.Web.Routing, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]public interface IRouteHandler{// MethodsIHttpHandler GetHttpHandler(RequestContext requestContext);}

Here, our questions are solved. The previously registered routing rules are all instantiated as Route objects, and the Route GetRouteData method is used to match routes, physicalFile and checkPhysicalUrlAccess in routing rules are used to instantiate an IHttpHandler instance and process requests.

Summary: shows the routing model of ASP. NET.

I will introduce the working principles of the ASP. NET routing model here, and hope to help you!

Articles you may be interested in:
  • Asp.net code hidden encoding model
  • ASP. NET MVC3
  • ASP. NET event model (suitable for learning articles)
  • How to find IHttpHandler in asp.net mvc Routing
  • ASP. NET Web API tutorial
  • Asp.net does not need to set iis to implement url rewriting similar to pseudo-static Routing
  • In ASP. NET, Form field values are automatically filled into the operation model.
  • ASP. NET MVC5 website development framework model, data storage, and business logic (3)
  • Add a route priority for ASP. net mvc and WebApi

Related Article

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.