PS: This is for the asp.net4.5 version, as if in the latest 5.0 version of the add Owin, thoroughly decoupled and Web server coupling, I have not yet studied, dare not raved that the 4.5 model applies 5.0.
action*0x1: A asp.net model of Dahua
First of all, let's understand the fate of the next request, and see the winding road in its life. As shown in the following illustration:
As shown in the beautiful scenery of the picture, we can see a "request" from the client browser, through the mountains to reach the server, The http.sys of the server's kernel module warmly entertained it, and after it was simply decorated, it parting with it, because HTTP.sys knew it was a dream "request," it should go where it was supposed to go, and sent it to IIS.
IIS is a magical piece of land, Here's a great God called Inetinfo.exe, so it went to the House of God W3SVC Service (Windows Service) Pray, hope to give him some instructions, the gods through the Bible (IIS configuration file), know that it is not a normal static file, can not send it directly back, it should be allowed to go to its people run Processing plants (that is, the corresponding Web site in the course of work) good practice.
The current processing plant eldest brother called W3wp.exe, in IIS6 before is aspnet_wp.exe, because there is no management of various processing plants between the site problem was dismissed (asp.net_ Wp.exe with a process to host all the sites, using the application domain segmentation, resulting in the interaction between the site, the incumbent eldest w3wp.exe through a Web site a process of the way to solve the problem, so smooth superior.
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 it opened the factory's production workshop (that is, when the first request arrived, started the asp.net running environment, then the request can be directly into the environment. , and asked the Workshop director Isapiruntime to take charge of it, the Director elated to welcome it (that is, the Isapiruntime call ProcessRequest (pr) method, access to the current request is the ECB handle), And let rustic it changed on the uniform clothing httpworkrequest (that is, the request for simple encapsulation), and then called the Monitor httpruntime, let the monitor to 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 of Httpworkrequest encapsulated into HttpContext), and then to the head of the Dormitory (HttpApplicationFactory) ready to call a group leader (HttpApplication) to lead it, the results found no team leader , the monitor had to recruit a new team leader.
Each team leader is a rigorous training to post, first to read into the factory guidelines global.asax (that is, first compiled Global.asax file), and then through the guidelines Application_Start method Test (that is, call the Application_Start method), This is the leader of a generation. The first thing for each new team leader is to assemble all the workshop modules and create a good shop line (by reading the configuration file, loading all the IHttpModule, and calling their Init methods, the General Init method is a registered pipe event, followed by the Buidstepmanager method , the corresponding Stepmanager is generated according to Classic mode or Integrated mode.
The new leader sees "request", apart directly starts the workshop pipeline, throws it in. Wearing a security uniform, HttpContext's "request." To sequentially pass through all the checkpoints in the pipeline (the ASP.net piping model), where the IHttpHandler type object is generated after the 7th checkpoint, and the ProcessRequest method processing request is executed after the 11th checkpoint, where "request" Get the perfect processing shape, generate the HttpResponse, and then through the rest of the pipeline, the realization of the dream of the request to follow the original way back. Between the 11th and 12 events in the previous illustration, the WebForm Page object processes the request (that is, the page life cycle).
At this point, a request of the ups and downs of Life said, you audience want to know how the routing module to play a role, but also please first the personal field, the lower right corner of a praise.
ACTION*0X2: Routing model parsing
Through the above we know that the leader HttpApplication object will be responsible for assembling all the IHttpModule, how does it load? We observe the Decompile 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 read the Run-time configuration file, then we open the Run-time configuration file to see.
Sure enough, add a System.WebRouting.UrlRoutingModule type here. Next, we use the decompile tool to look at this type of source code:
As we expected urlroutingmodule implement the IHttpModule interface, what do we look at its Init method?
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 7th Event Postresolverequestcache registration Method Onapplicationpostresolverequestcache, then this method is what?
public virtual void Postresolverequestcache (HttpContextBase context) {Routedata Routedata = this.
Routecollection.getroutedata (context);//Match route, get matching result routedata. if (routedata!= null) {Iroutehandler Routehandler = Routedata.routehandler; if (Routehandler = null) {throw new Invali Doperationexception (String. Format (CultureInfo.CurrentCulture, SR.
GetString ("Urlroutingmodule_noroutehandler"), new object[0]); } if (! ( Routehandler is Stoproutinghandler)} {requestcontext RequestContext = new RequestContext (context, routedata);
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 new InvalidOperationException (St Ring. 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);//mapping: Processing a request with the current IHttpHandler object. }
}
}
}
Code already commented, 3 steps: match route → get the IHttpHandler object → map that handles the current request: processing the request with the current IHttpHandler object. The PR method of the IHttpHandler object is then invoked 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 a implementation of the IHttpModule interface class, its Init method is to register a method on the 7th event, the method first match the route, if the match is successful, then use the matching result routedata in the I The HttpHandler object is mapped to the current context so that the IHttpHandler object handles the request after the 11th and 12 events.
Then the question comes, when route object is injected into, IHttpHandler object is who?
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", "*");
Mode one:
//Routes new object of route type by RouteTable static object.
RouteTable.Routes.Add ("app", New Route ("App/{name}", Defaults, New Myroutehandler ());
Mode two:
//Add a routing rule through the RouteTable static object routes extension method.
RouteTable.Routes.MapPageRoute ("Default", "App/{name}", "~/webform1.aspx", false, defaults);
}
This is one of the two ways that we often add routing rules, in the form of an instance of the Myroutehandler type we write ourselves as arguments, which is actually returning a IHttpHandler object through the Iroutehandler interface.
<summary>
///implements the type of Iroutehandler interface
///</summary>
internal class Myroutehandler: Iroutehandler
{public
IHttpHandler Gethttphandler (requestcontext requestcontext)
{
//Returns a Page object, Used to process requests. return
new WebForm1 ();
}
In fact, there is no intrinsic difference between the two ways, because the way of the second route by the rule parameter will instantiate a route object.
The source code of our analysis mode two:
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 found to instantiate a route object, where the parameters PhysicalFile and checkphysicalurlaccess are used to instantiate the Pageroutehandler object, and the source code is as follows:
public class Pageroutehandler:iroutehandler
{
This is a type of implementation of the Iroutehandler interface, and this interface has 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")]
Public interface Iroutehandler
{
//Methods
IHttpHandler gethttphandler (RequestContext requestcontext);
}
Here our question is solved, the original we registered routing rules are instantiated into the route object, route Getroutedata method to match the route, The PhysicalFile and checkphysicalurlaccess in the routing rules are used to instantiate a IHttpHandler instance to process the request.
Summary: The asp.net routing model is shown in the following illustration
About the ASP.net routing model working principle small series to introduce to everybody here, hope to be helpful to everybody!