MVC Request processing process (i)

Source: Internet
Author: User

The routing system obtains the routing data first, and in the UrlRoutingModule object that implements the IHttpModule interface, registers the HttpApplication Postresolverequestcache to Parse the routing data and map the request ;

protected virtual void Init (HttpApplication application) {if (application.      Context.items[urlroutingmodule._contextkey]! = null) return; Application.      Context.items[urlroutingmodule._contextkey] = Urlroutingmodule._contextkey; Application. Postresolverequestcache + = new EventHandler (this. Onapplicationpostresolverequestcache); }public virtual void Postresolverequestcache (HttpContextBase context) {Routedata Routedata = this.      Routecollection.getroutedata (context);      if (Routedata = = null) return;     Iroutehandler Routehandler = Routedata.routehandler; if (Routehandler = = null) throw new InvalidOperationException (string. Format ((IFormatProvider) CultureInfo.CurrentCulture, System.Web.SR.GetString ("Urlroutingmodule_noroutehandler"),      New object[0]));      if (Routehandler is Stoproutinghandler) return;      RequestContext RequestContext = new RequestContext (context, routedata); Context.      Request.requestcontext = RequestContext; ihttphAndler HttpHandler = Routehandler.gethttphandler (RequestContext);//Get Mvchandler if (HttpHandler = = null) THR ow new InvalidOperationException (string. Format ((IFormatProvider) CultureInfo.CurrentUICulture, System.Web.SR.GetString ("Urlroutingmodule_nohttphandler")      , new Object[1] {(object) Routehandler.gettype ()})); else if (HttpHandler is Urlauthfailurehandler) {if (! formsauthenticationmodule.formsauthrequired) throw new HttpException (401, System.Web.SR.GetString ("Assess_denied_        Description3 "));      Urlauthorizationmodule.reporturlauthorizationfailure (HttpContext.Current, (object) this); } else context. Remaphandler (HttpHandler); }

The routing data has a Iroutehandler Routehandler property, which defaults to Mvcroutehandler when registering a route

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, (iroutehandler) New Mvcroutehandler ())      {        Defaults = Routecollectionextensions.createroutevaluedictionary (defaults),        Constraints = Routecollectionextensions.createroutevaluedictionary (constraints),        datatokens = new RouteValueDictionary ()      };      if (namespaces! = null && namespaces. Length > 0)        route. Datatokens["namespaces"] = (object) namespaces;      Routes. ADD (name, (routebase) route);      return route;}

The

Routehandler has a Gethttphandler method to get the HttpHandler that the current request is mapped (session state is also set at this stage, by Controllerfactory.getcontrollersessionbehavior () method)

 public Mvcroutehandler (Icontrollerfactory controllerfactory) {this._contr   Ollerfactory = controllerfactory; } protected Virtual Sessionstatebehavior Getsessionstatebehavior (RequestContext requestcontext) {string Controllerna      me = (string) requestcontext.routedata.values["Controller"; if (string. Isnullorwhitespace (controllername)) throw new InvalidOperationException (mvcresources.mvcroutehandler_      Routevalueshasnocontroller); else return (this._controllerfactory?? ControllerBuilder.Current.GetControllerFactory ()). Getcontrollersessionbehavior (RequestContext, controllername); } protected Virtual IHttpHandler Gethttphandler (RequestContext requestcontext) {requestContext.HttpContext.SetSess Ionstatebehavior (this.      Getsessionstatebehavior (RequestContext));   Return (IHttpHandler) new Mvchandler (RequestContext); }

The

Returns a IHttpHandler mvchandler object, The Processrequestinit method is called in the request-handling method ProcessRequest of Mvchandler, which is the following code:

protected internal virtual void ProcessRequest (HttpContextBase HttpContext) {IController controller;      Icontrollerfactory Factory; This. Processrequestinit (HttpContext, out controller, out factory);//Get to the current controller object try {controller. Execute (this. RequestContext);//Make further method calls} finally {factory.  Releasecontroller (Controller);//release after completion}}private void Processrequestinit (HttpContextBase HttpContext, out IController      Controller, out Icontrollerfactory factory) {httpcontext-current = HttpContext.Current;        if (current! = NULL) {bool? nullable = validationutility.isvalidationenabled (current); if (!nullable. GetValueOrDefault ()? 0: (Nullable. HasValue?      1:0))! = 0) validationutility.enabledynamicvalidation (current); } this.      Addversionheader (HttpContext); This.     Removeoptionalroutingparameters (); String requiredstring = this.      RequestContext.RouteData.GetRequiredString ("Controller");Factory = this.      Controllerbuilder.getcontrollerfactory (); Controller = Factory. Createcontroller (this.     RequestContext, requiredstring);      if (Controller = null) return; throw new InvalidOperationException (string. Format ((IFormatProvider) CultureInfo.CurrentCulture, Mvcresources.controllerbuilder_factoryreturnednull, new Object[2] {(object) factory.  GetType (), (object) requiredstring}); }

The method of creating a controller through factory Controllerfactorycontroller is described in the above method : [Controller creation]. the Execute method of the controller is implemented in its base class Controllerbase.

protected virtual void Execute (RequestContext requestcontext) {      if (RequestContext = = null)        throw new ArgumentNullException ("RequestContext");      if (Requestcontext.httpcontext = = null)        throw new ArgumentException (mvcresources.controllerbase_ Cannotexecutewithnullhttpcontext, "RequestContext");      This. Verifyexecutecalledonce ();      This. Initialize (RequestContext);      using (Scopestorage.createtransientscope ())        

Overridden a method in its subclass controller Executecore

protected override void Executecore () {this      . Possiblyloadtempdata ();      Try      {        //Get Action Method name       String requiredstring = this. Routedata.getrequiredstring ("action");        if (this. Actioninvoker.invokeaction (this. ControllerContext, requiredstring))         return;        This. Handleunknownaction (requiredstring);      }      Finally      {this        . Possiblysavetempdata ();      }}

The Actioninvoker property is used here, which corresponds to an object that implements the Iactioninvoker interface! The default is get in this. The Createactioninvoker () method is the Asynccontrolleractioninvoker object (This is the busiest object)!

[Next Article]

MVC Request processing process (i)

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.