Asp.net MVC Request Life Cycle



While programming with Asp.net MVC, you should be aware of the life of an Asp.net MVC request from birth to death. In this article, I am going to expose the Asp.net MVC Request Life cycle. There are seven main steps that happen when you make a request to an Asp.net MVC web applications. For more details refer Detailed ASP.NET MVC Pipeline


  1. RoutingAsp.net Routing is the first step in MVC request cycle. Basically it is a pattern matching system that matches the request’s URL against the registered URL patterns in the Route Table. When a matching pattern found in the Route Table, the Routing engine forwards the request to the corresponding IRouteHandler for that request. The default one calls the ​​MvcHandler​​. The routing engine returns a 404 HTTP status code against that request if the patterns is not found in the Route Table.When application starts at first time, it registers one or more patterns to the Route Table to tell the routing system what to do with any requests that match these patterns. An application has only one Route Table and this is setup in the Global.asax file of the application.

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

  10. MvcHandlerThe MvcHandler is responsible for initiating the real processing inside ASP.NET MVC. MVC handler implements IHttpHandler interface and further process the request by using ​​ProcessRequest​​ method as shown below:

  11. protected internal virtual void ProcessRequest(HttpContextBase httpContext)
  12. {
  13. SecurityUtil.ProcessInApplicationTrust(delegate {
  14. IController controller;
  15. IControllerFactory factory;
  16. this.ProcessRequestInit(httpContext, out controller, out factory);
  17. try
  18. {
  19. controller.Execute(this.RequestContext);
  20. }
  21. finally
  22. {
  23. factory.ReleaseController(controller);
  24. }
  25. });
  26. }

  27. ControllerAs shown in above code, MvcHandler uses the IControllerFactory instance and tries to get a IController instance. If successful, the Execute method is called. The IControllerFactory could be the default controller factory or a custom factory initialized at the ​​Application_Start​​ event, as shown below:

  28. protected void Application_Start()
  29. {
  30. AreaRegistration.RegisterAllAreas();
  31. RegisterRoutes(RouteTable.Routes);
  32. ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
  33. }

  34. Action Execution
     
    Once the controller has been instantiated, Controller's ActionInvoker determines which specific action to invoke on the controller. Action to be execute is chosen based on attributes ​​ActionNameSelectorAttribute​​ (by default method which have the same name as the action is chosen) and ​​ActionMethodSelectorAttribute​​(If more than one method found, the correct one is chosen with the help of this attribute).
  35. View Result
    The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.
  36. View EngineThe first step in the execution of the View Result involves the selection of the appropriate View Engine to render the View Result. It is handled by ​​IViewEngine​​ interface of the view engine. By default Asp.Net MVC uses​​WebForm​​ and ​​Razor​​ view engines. You can also register your own custom view engine to your Asp.Net MVC application as shown below:

  37. protected void Application_Start()
  38. {
  39. //Remove All View Engine including Webform and Razor
  40. ViewEngines.Engines.Clear();
  41. //Register Your Custom View Engine
  42. ViewEngines.Engines.Add(new CustomViewEngine());
  43. //Other code is removed for clarity
  44. }

  45. View
    Action method may returns a text string,a binary file or a Json formatted data. The most important Action Result is the ViewResult, which renders and returns an HTML page to the browser by using the current view engine.

What do you think?

I hope you will enjoy the Asp.Net MVC request life cycle while programming with Asp.Net MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.