ASP.NET MVC Application Request life cycle

This article describes about ASP.NET MVC request life cycle, it explains how request flows from user browser to MVC application and vice versa.

This gives you detail description of ASP.NET MVC request steps like routing, MvcHandler, Controller, Action Execution, View Result, View Engine and View.

Below picture gives you detail flow of ASP.NET MVC page life cycle

asp.net mvc application request life cycle

Routing:

ASP.NET MVC routing is nothing but matching incoming URI to action. MVC requests works on basis of routing data which is in RouteTable. At very first request of application RouteTable is empty. Application Start event should fill the required Routes. Depending on the url used by client browser UrlRoutingModule uses RouteTable to retrieve correct RouteData to define which Controller and action should be invoked.

If UrlRoutingModule gets correct RouteData, it creates RequestContext object which represent current HttpContext and RouteData. Routing engine forwards the RequestContext object to corresponding IRouteHandler

If UrlRoutingModule does not get matching controller and its action for incoming request it returns HTTP status code 404 (Page not found).

Below example shows how you can create mapping of routes in RegisterRoutes method called from Application Start Event.

                
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default"
        , "{controller}/{action}/{id}"
        , new { controller = "Security", 
                action = "Login", id = UrlParameter.Optional }                
    );
}
            

routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); specifies any request for .axd should be ignored and should not process.

routes.Maproute specifies route name as default and matching request should be forward to Security controller and Login method.

For each mapping Route name should be unique. You can remove particular route by RouteTable.Routes.Remove(“route item”) method. See more about ASP.NET MVC routing with example


IRouteHandler Interface

It exposes a single method GetHttpHandler, which provides RouteHandler class instance based on RouteContext data to process request. All Routes which are added to RouteTable by MapRoute extension method are handled by default RouteHandler that is MvcRouteHandler class defined in the System.Web.Mvc namespace.

Below is interface definition

                
public interface IRouteHandler
{
    IHttpHandler GetHttpHandler(RequestContext requestContext);
}            
            

MVCHandler

MvcHandler is responsible for initiate actual processing of ongoing request and generate response. MvcHandler gets information of current request through RequestContext object passed to its constructor.

Below is the constructor code for MVChandler

                
public MvcHandler(RequestContext requestContext)
{
}
                    
            

MvcHandler class implements three interfaces : IHttpAsyncHandler, IHttpHandler and IRequiresSessionState. IHTTPHandler's ProcessRequest method actually process the ongoing request.

The ProcessRequest method is implemented in MvcHandler as below

                
protected internal virtual
         void ProcessRequest(HttpContextBase httpContext)
{
    SecurityUtil.ProcessInApplicationTrust(delegate {
        IController controller;
        IControllerFactory factory;
        this.ProcessRequestInit(httpContext, out controller, out factory);
        try
        {
            controller.Execute(this.RequestContext);
        }
        finally
        {
            factory.ReleaseController(controller);
        }
        });
}
                    
            

The Controller Executes

MvcHandler uses IControllerFactory instance and to get IController object. All Mvc controllers implement IController interface. This interface has Execute method which actually execute your action method code. So Mvc Controller executes method from IController interface.

At the beginning of Execute method it creates TempData object. The Execute method get Action from RouteData based on ongoing request. Then MVC Controller call ControllerActionInvoker which creates a list of parameters coming with URL. These parameters are collected from request objects Parameters collection. This parameter list will be passed to Controller Action method.

Finally it calls InvokeAction method to execute action.


Action Execution

After the particular controller gets instantiated ActionInvoker determines which specific Action method needs to be execute. ActionInvoker uses ActionNameSelectorAttribute and ActionMethodSelectorAttribute to select Action method for execution. Action method always returns ActionResult.

If you do not want any specific method should not accessible through public URI, you can mark that method with [NonAction] attribute.


ViewEngine

If ActionResult returns a ViewResult, execution pipeline selects appropriate ViewEngine to render ViewResult. It is taken care by view engine's interface IviewEngine. ASP.NET MVC has Webform and Razor view engines. You can use any of them to develop Views. You can also create your own ViewEngines and use it. For performance reason it is better to remove ViewEngines which are not required. Below code clear all ViewEnginees and register only Razor

                
protected void Application_Start() 
{ 
    //Remove All Engine
    ViewEngines.Engines.Clear();

    //Add Razor Engine
    ViewEngines.Engines.Add(new RazorViewEngine());
} 
                    
  

Render View Result

Action method can return a simple string value, binary file, JSON data or JavaScript block. And the most important is ViewResult. It returns response in form of HTML which can be rendered to browser using ViewEngine.

Action method get required or optional user input as part of URL. Then it executes the code and prepare response for current request.

For each Action method controller executes either RedirectToAction or RenderView method. The RenderView method uses a class named ViewLocator to find corresponding View to render.

Then If there is MasterPage or ViewData then it get set appropriately and finally the RenderView method get called on ViewPage.

Speak your mind :
Leave a comment for this article on dotnetbloogers.com