Friday, December 28, 2012

MVC Request Life Cycle


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 Lifecycle. There are six main steps that happen when you make a request to an Asp.net MVC web applications:
  1. Routing

    Asp.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 appropriate handler for that request. Otherwise, the routing engine returns a 404 HTTP status code against that request.
    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.
    1. public static void RegisterRoutes(RouteCollection routes)
    2. {
    3. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    4. routes.MapRoute( "Default", // Route name
    5. "{controller}/{action}/{id}", // URL with parameters
    6. new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    7. );
    8. }
  2. MvcHandler

    The handler returned from the RouteTable will always be an MvcHandler and represents a particular RouteContext. Actually, MvcHandler creates a controller, and also executes the controller.
  3. Controller

    The controller determines which action method of the controller class to call, and then calls that method
  4. 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.
  5. View Engine

    Now the ViewResult calls into the current view engine to render the view. Controller is responsible only for preparing the data and decides which view to display by returning a ViewResult instance.
  6. View

    The data rendered by the current view engine is displayed on the view.

No comments:

Post a Comment