ASP.Net MVC Request Life Cycle

Introduction

While programming with ASP.Net MVC, we should understand 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.

 

  1. protected void Application_Start()  
  2. {  
  3.     AreaRegistration.RegisterAllAreas();  
  4.     RegisterRoutes(RouteTable.Routes);  
  5. }  
  6.   
  7. public static void RegisterRoutes(RouteCollection routes)  
  8. {  
  9.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  10.     routes.MapRoute(  
  11.         "Default"// Route name  
  12.         "{controller}/{action}/{id}"// URL with parameters  
  13.         new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults  
  14.     );  
  15. }

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

  1. public class CustomControllerFactory : IControllerFactory  
  2. {  
  3.     public IController CreateController(RequestContext requestContext, string controllerName)  
  4.     {  
  5.         //TODO: IoC implementation or Creating controller from request context.   
  6.         return null;  
  7.     }  
  8.     public void ReleaseController(IController controller)  
  9.     {  
  10.         var disposable = controller as IDisposable;  
  11.         if (disposable != null)  
  12.         {  
  13.             disposable.Dispose();  
  14.         }  
  15.     }  
  16.     public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)  
  17.     {  
  18.         throw new NotImplementedException();  
  19.     }  
  20. }  
  21.   
  22. public class MvcApplication : System.Web.HttpApplication  
  23. {  
  24.     protected void Application_Start()  
  25.     {  
  26.         AreaRegistration.RegisterAllAreas();  
  27.         ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());  
  28.         RegisterRoutes(RouteTable.Routes);  
  29.     }  
  30. }

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

  1. public class MyViewEngine : IViewEngine  
  2. {  
  3.   
  4.     public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)  
  5.     {  
  6.             //Finds the partial view by using the controller context.  
  7.         return null;  
  8.     }  
  9.   
  10.     public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)  
  11.     {  
  12.         //Finds the view by using the controller context.  
  13.         return null;  
  14.     }  
  15.   
  16.     public void ReleaseView(ControllerContext controllerContext, IView view)  
  17.     {  
  18.         //Releases the view by using the controller context.  
  19.     }  
  20. }  
  21. public class MvcApplication : System.Web.HttpApplication  
  22. {  
  23.     protected void Application_Start()  
  24.     {  
  25.         AreaRegistration.RegisterAllAreas();  
  26.         RegisterGlobalFilters(GlobalFilters.Filters);  
  27.         //Clear all current register view engine  
  28.         ViewEngines.Engines.Clear();  
  29.         //Register Custom View Engine  
  30.         ViewEngines.Engines.Add(new MyViewEngine());  
  31.         RegisterRoutes(RouteTable.Routes);  
  32.     }  
  33. }

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.


Similar Articles