Virtual Classes Logo          Virtual Classes
    Read Anytime,Anywhere

MVC Request Life Cycle

In a MVC application,Physical page does not exists for a specific request like we have in All the incoming requests are routed to a special class called Controller class. The controller class is responsible for generating the response and sending the response back to the browser. When a browser makes a request of a MVC application, it basically calls the action method of a controller.

ASP.NET MVC Request Life Cycle
Whenever a browser makes a request, it goes through following steps-
1-Routing-ASP.NET Routing is the first step in MVC request life cycle. ASP.NET MVC routing is basically a pattern matching system that matches the request’s URL against the URL patterns registered in the Route Table.
Route Table in MVC keeps the route information. Every ASP.NET MVC application has a RouteTable class. This RouteTable is responsible for mapping the MVC requests to a specific controller's ActionMethod. Whenever the application starts, the Application_Start event will be fired, it will call the RegisterRoutes()method and pass all the available routes of the MVC application as a parameter. RegisterRoutes()method adds the routes to the Routes property of the System.Web.Routing.RouteTable class. The Routes property is of type RouteCollection.
The MapRoute() adds all routes to the RouteTable and associates the RouteHandlers with the routes. When an ASP.NET MVC application handles a request, the application iterates through the collection of routes in the Routes property to find the route that matches the format of the URL requested. The application uses the first route that matches with the requested URL in the collection . So most specific route should be added at the first and general routes are at the last. An application can have only one Route Table and this is set up in the Global.asax file of the application. Depending on the url requested by client browser, UrlRoutingModule uses RouteTable to retrieve RouteData to indentify that which Controller and action method will be invoked.
The UrlRoutingModule intercepts each incoming request, it finds a matching RouteData from RouteTable and instantiates MVCHandler which is basically a HttpHandler.
Basically,MVC check for the route information in route table for incoming request,When a matching pattern is found in the Route Table, the Routing engine forwards the request to the corresponding IRouteHandler. The default one calls the MvcHandler. if there is not mathcing pattern in the Route Table then the routing engine returns a 404 HTTP status code

Register a route in MVC

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");    specifies that any request for .axd should be ignored and should not be processed.
routes.Maproute    specifies default route and matching request should be forward to Home controller's action method (here you can define your default controller and action method).
Route name should be unique in the route table.
You can remove particular route by RouteTable.Routes.Remove("RouteName") method.

2-MVC Handler-The MVC Handler is responsible for the real processing of request and generate response in MVC. MVCHandler gets information of current request through RequestContext object passed to its constructor. MVCHandler class implements three interfaces : IHttpAsyncHandler, IHttpHandler and IRequiresSessionState. MVC handler implements IHttpHandler interface and process the request by using ProcessRequest method. The ProcessRequest() method takes an instance of HttprContext and is responsible for processing the request and generating the response. When MVCHandler executes, it calls the ProcessRequest() method that in turn calls the ProcessRequestInit() method. The ProcessRequestInit() method creates a ControllerFactory and a Controller. The Controller is created from a ControllerFactory. There is a ControllerBuilder class that will set the ControllerFactory.
MVCHandler uses the IControllerFactory instance and tries to get a IController instance. If successful, the Execute method is called. then it Gets the ActionMethod from the RouteData based on the URL. The ActionMethod returns an instance of a class inherited from the ActionResult class and the View Engine renders a view as a web page. All Mvc controllers implement IController interface. This interface has Execute method which actually execute your action method code. 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.
The ViewBag, ViewData, TempData and so on properties of the ControllerBase class is initialized. These properties are used for ing data from the View to the Controller or vice-versa or among action methods.

3-Action Execution-Once the controller has been instantiated, ActionInvoker determines which action of the controller needs to be invoke. Action invoker uses ActionNameSelectorAttribute (by default method which have the same name as the action is choosen) and ActionMethodSelectorAttribute(If more than one method found, the correct one is chosen with the help of this attribute). 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.

4-View Result-The action method gets the user input,it creates response, 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- The execution of the View Result involves the selection of the appropriate View Engine to render the View Result. 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 create your views. You can also create your own ViewEngines and use it. For performance reason it is better to remove ViewEngines which are not required.

6-View-Action method can return string value, binary file, JSON data or JavaScript block. The most important Action Result is the ViewResult,which renders and returns an HTML page to the browser by using the current view engine. 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 create response for the request. If there is MasterPage or ViewData then it get set appropriately and finally the RenderView method get called on ViewPage.