The Asp.net application pipeline specifically addresses ” time ” when processing user requests . Understanding the Asp.net lifecycle directly affects the efficiency of our pages and controls.

When an HTTP request is handed over from IIS to the Asp.net runtime at what time does Asp.net MVC gain control and process the request? What is theprocess ?

With IIS7 in asp.net application life cycle, for example, the figure below from MSDN one of HTTP diagram of request processing occurrence of the event, behind me list a complete list of events. Since Asp.net Mvc is still based on the Asp.net runtime, it must intercept the request during the lifecycle of the Asp.net application. The first reaction is of course to go inside the web.config , we can see the configuration section of the UrlRoutingModule :

< add  name ="UrlRoutingModule"  type ="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

The following is a matter of course, open this assembly with Reflector you can see the following code:

 protected virtual void Init(HttpApplication application)
    {
        application.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache);
        application.PostMapRequestHandler += new EventHandler(this.OnApplicationPostMapRequestHandler);
    }

Seeing our first question here actually has an answer: the timing is in PostResolveRequestCache and PostMapRequestHandler.

ResolveRequestCache event Occurs when ASP.NET finishes an authorization event to let the caching modules serve requests from the cache, bypassing execution of the event handler (for example, a page or an XML Web service).

Source document < http://msdn.microsoft.com/en-us/library/system.web.httpapplication.resolverequestcache.aspx >

 

 PostMapRequestHandler event Occurs when ASP.NET has mapped the current request to the appropriate event handler.

Source document < http://msdn.microsoft.com/en-us/library/system.web.httpapplication.postmaprequesthandler.aspx >

 

We used the Asp.net Mvc template in VS2008 to create a demo to complete the follow-up discussion. What happened when we accessed /Home ?

  1. Request request coming
  2. IIS hands over processing rights to ASP.NET based on request characteristics
  3. UrlRoutingModule matches the current request in the Route Table
  4. UrlRoutingModule in RouteCollection lookup Request match RouteHandler, the default is MvcRouteHandler MvcRouteHandler create MvcHandler instance .
  5.  MvcHandler executes ProcessRequest.
  6.  MvcHandler uses IControllerFactory to get an instance of the IController interface and find the corresponding HomeController.
  7.  Trigger the HomeController ‘s Index method according to Request
  8. Index stores the execution result in ViewData
  9. HomeController ‘s Index method returns ActionResult
  10. Views / Home / Index.aspx will ViewData presented on page
  11. Index.aspx executes the ProcessRequest method
  12. Index.aspx executes the Render method output to the client

 

    By reading the source code of Asp.net Mvc we can get a more detailed process I will ignore the branch as much as possible and emphasize the process of request processing. We cut in from the Global.asax.cs file Here is a sample code Here is the routing table initialized please pay special attention to the comment section :

public class MvcApplication : System.Web.HttpApplication
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
               
                //The controller route value is a special value that the System.Web.Mvc.MvcHandler class uses to call into the IControllerFactory interface.
                //The basic route handler is an instance of IRouteHandler named MvcRouteHandler.
                //We have complete control and could provide our own implementation of IRouteHandler if we wished.
                routes.MapRoute(
                    "Default",                                              // Route name
                    "{controller}/{action}/{id}",                           // URL with parameters
                    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
                );
             
    
            }
    
            protected void Application_Start()
            {
                RegisterRoutes(RouteTable.Routes);
            }

UrlRoutingMoudule in PostResolveRequestCache from stage RouteCollection obtain the current request RouteData.RouteData includes a request processing corresponding Controller and the Action, the RouteData process through the action request .RouteData extracts RouteHandler where default MvcRouteHandler, MvcRouteHandler obtain HttpHandler, default here Is the MvcHandler.

public virtual void PostResolveRequestCache(HttpContextBase context)
{
    RouteData routeData = this.RouteCollection.GetRouteData(context);
    if (routeData != null)
    {
        IRouteHandler routeHandler = routeData.RouteHandler;
        if (routeHandler == null)
        {
            throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, RoutingResources.UrlRoutingModule_NoRouteHandler, new object[0]));
        }
        if (!(routeHandler is StopRoutingHandler))
        {
            RequestContext requestContext = new RequestContext(context, routeData);
            IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);
            if (httpHandler == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, RoutingResources.UrlRoutingModule_NoHttpHandler, new object[] { routeHandler.GetType() }));
            }
            RequestData data2 = new RequestData();
            data2.OriginalPath = context.Request.Path;
            data2.HttpHandler = httpHandler;
            context.Items[_requestDataKey] = data2;
            context.RewritePath("~/UrlRouting.axd");
        }
    }
}

The MvcHandler .ProcessRequest () is first used HttpContextWrapper of HttpContext encapsulation encapsulation in order to obtain the purpose of decoupling testability Then the RequestContext.RouteData extraction Controller name 
ControllerBuilder.GetControllerFactory -> ControllerFactory CreateController -> IController .Execute

ControllerBase implements the IController interface When Initialize , the RequestContext is encapsulated into a ControllerContext . The Controller inherits from ControllerBase and implements the abstract method ExecuteCore().

In ExecuteCore in , Controller first from RouteData get in ActionName, and then perform ActionInvoker.InvokeAction .

In ActionInvoker we can see a variety of Filter, which is a AOP practice In Action execution method performed before and after a number of waysThere are four Filter: ActionFilters ResultFilters AuthorizationFilters ExceptionFilters The four Filter is not closed has a corresponding interface ,which is just four default implementation .Filter execution order is : AuthorizationFilter —> Filter.OnActionExecuting the Action —> Method, the Action —> ActionFilter.OnActionExecuted. InvokeActionMethodWithFilters returned result is ActionExecutedContext Next will the ControllerPerformingOnResultExecuting method .ActionResult execution result may be ViewResult, JsonResult, RedirectResult, ContentResult, or custom Result type .

If the returned type is ViewResult, let’s take a look at the ViewReuslt inheritance relationship : ViewResult–>ViewResultBase–>ActionResult, ViewResult contains two properties View and ViewEngineCollection , which actually contains the implementation of two interfaces : IViewEnginedefines how Positioning View/Partial View.IView defines how RenderView. The default implementation is WebFormView and WebFormViewEngine.

Filter OnResultExecuted is the last step you can catch exceptions here We also said that there are ExceptionFilters, if the exceptions in the previous process are not caught then they will eventually bubble to ExceptionFilters.

  • Get ActionName in RouteData
  • ActionInvoker.InvokeAction
  • By ControllerContext get ControllerDescriptor
  • FindAction – Get ActionDescriptor
  • GetFilters
  • ModelBinder converts the data in the Request into the parameters required by the Action method.
  • AuthorizationFilter
  • Action Filter.OnActionExecuting
  • Action
  • ActionFilter.OnActionExecuted
  • ResultFilter.OnResultExecuting
  • ActionResult Execution
  • ResultFilter.OnResultExecuted
  • WebFormViewEngine.CreateView
  • WebFormView.Render
  • ResultFilter.OnExecuted

Control returns to HttpApplication to complete the subsequent life cycle .