ASP.Net MVC Request Life Cycle

Introduction

While programming with ASP.Net MVC, we should ndeerstand how ASP.NET MVC processes our requests and how many main stages there are in this process. There are primarily seven stages in the ASP.Net Request Life Cycle.

MVC.jpg

Routing

Routing is the first stage of the MVC Request Life Cycle. All requests to an ASP.NET MVC based application first pass through an UrlRoutingModule object (that is nothing but a HTTP module). The RouteCollection property of UrlRoutingModule contains all routes registered in the Global.asax file. UrlRoutingModule searches and matches for the route that has a URL. When a match is found, it retrieves the IRouteHandler object for that route. The route handler helps to get an IHttpHandler object and that is a HTTP handler for the current request. Route objects are added to the RouteTable object.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
}


MVC Request Handler (MVCRouteHandler)

MVC handler is responsible for initiating MVC applications. The MvcRouteHandler object creates an instance of the MvcHandler and passes the instance of RequestContext to MvcHandler. MvcHandler is implemented from ITttpHandler and it cannot map as a handler. This class does not support a parameterless constructor. It takes RequestContext as a parameter.

Controller

MVCHandler receives a controller instance from the MVC controller factory (IControllerFactory). This controller handles further processing of the request. The MVCHandler object uses RequestContext (passed as a constructor parameter) instance to identify the IControllerFactory object to create the controller instance. The MvcHandler instance calls the Execute method of controller.

Create and register Custom Controller Factory

public class CustomControllerFactory : IControllerFactory
{
    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        //TODO: IoC implementation or Creating controller from request context. 
        return null;
    }
    public void ReleaseController(IController controller)
    {
        var disposable = controller as IDisposable;
        if (disposable != null)
        {
            disposable.Dispose();
        }
    }
    public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
    {
        throw new NotImplementedException();
    }
}

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
        RegisterRoutes(RouteTable.Routes);
    }
}

Action invocation

The Controller class is inherited from the ControllerBase. The ControllerActionInvoker object is associated with a controller object that is responsible for determining which action of the controller is called, then the controller invokes this action method. The selected action is called based on the ActionNameSelectorAttribute attribute (by default it is the same as the Action name). This ActionNameSelectorAttribute helps us to select the correct action method if more than one action method is found that has the same name. In this stage the action filters are also applied. There are four types of filters, AuthorizationFilters, ExceptionFilters, ActionFilters and ResultFilters. Action invoker uses a Model Binder object if the action method has argument(s).

A Model Binder provides a simple way to map posted form value(s). Model Binder is just like a type converter, because it can convert a HTTP Request into an object and pass it to the action method.

Execute Result

The action method is responsible for receiving user input and creating appropriate response data and then executing the result by result type. MVC supports many builtin action result return types, like ViewResult, RidirectToRouteResult, RedirectResult, ContentResult, EmptyResult and JsonResult. We can create our own action result return type.

Refer: Action Return Result Type

View Engine

View Result is responsible for selecting and involving the appropriate View Engine. A View Engine is responsible for rendering HTML to the browser. The View Engine template has different syntax to implement the view. Currently there are four builtin View Engines (Razor, ASPX, Spark and NHaml) supported by MVC. We can also create our own custom View Engine to render a view. All the View Engines may not be supported in all versions of MVC. We can also use multiple View Engines simultaneously in ASP.NET MVC.

Creating Custom View Engine

public class MyViewEngine : IViewEngine
{

    public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
    {
            //Finds the partial view by using the controller context.
        return null;
    }

    public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
    {
        //Finds the view by using the controller context.
        return null;
    }

    public void ReleaseView(ControllerContext controllerContext, IView view)
    {
        //Releases the view by using the controller context.
    }
}
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        //Clear all current register view engine
        ViewEngines.Engines.Clear();
        //Register Custom View Engine
        ViewEngines.Engines.Add(new MyViewEngine());
        RegisterRoutes(RouteTable.Routes);
    }
}

View

An Action method may return JSON data, a simple string or file. Commonly an Action Result returns a ViewResult. ViewResult is rendered and returned as an HTML page to the browser using a View Engine.

Conclusion

This article helps us to understand the Request Life Cycle in MVC.
 

Up Next
    Ebook Download
    View all
    Learn
    View all