Monday, 27 January 2014

MVC Request Life Cycle

What is MVC?

The Model-View-Controller (MVC) is an architectural pattern, which separates an application into three main components: the model, the view, and the controller. 



  • The “View” is responsible for presentation (look and feel) or the user interface (UI) layer of MVC web application.
  • The “Controller” is responsible to handle the end user request and work with model and finally select view to render the UI.
  • “Model” represents the real world object that manages the behavior and provides data to the “View”.

 How MVC page request is being handled?

When request comes from client to the server, a following step are performed before sending response to the client (browser).


1. Routing
Routing is the first stage of the MVC Request Life Cycle. Whenever browser makes a request against an ASP.NET MVC application, the request is intercepted by the UrlRoutingModule. The RouteCollection property of UrlRoutingModule contains all routes registered in the Global.asax file.
// Register Routes in Global.asax.
---------------------------------------------------------------------------------------------------

protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();
  // Required method call at first time application run.
    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
  );
}
---------------------------------------------------------------------------------------------------
Properties of Route

  • Route Name: A route is a URL pattern that is mapped to a handler. A handler can be a controller in the MVC application that processes the request. 
  • URL Pattern: A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL that are delimited by the slash (/) character.
  • Defaults: The defaults are an object that contains default route values for route.


2. MvcHandler
The responsibility of MvcHandler class is generate the response for the ongoing request being processed. It receives information from the RequestContext passed to its constructor, in the implementation of the GetHttpHandler() method in the MvcRouteHandler class. The MvcHandler class implements three interfaces : IHttpAsyncHandler, IHttpHandler and IRequiresSessionState.

IRequiresSessionState interface, which specifies that the current HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods in it.

IHttpHandler interface defines the contract that a class must implement in order to synchronously  process HTTP Web requests using HTTP handler. It exposes a ProcessRequest() method.

IHttpAsyncHandler interface is the asynchronous version of IHttpHandler interface.
---------------------------------------------------------------------------------------------------

void IHttpHandler.ProcessRequest(HttpContext httpContext)
{
    ProcessRequest(httpContext);
}

protected virtual void ProcessRequest(HttpContext httpContext)
{
    HttpContextBase iHttpContext = new HttpContextWrapper(httpContext);
    ProcessRequest(iHttpContext);
}

protected internal virtual void ProcessRequest(HttpContextBase httpContext)
{
     // Get the controller type
    string controllerName = RequestContext.RouteData.GetRequiredString("controller");

    // Instantiate the controller and call Execute
    IControllerFactory factory = ControllerBuilder.GetControllerFactory();
    IController controller = factory.CreateController(RequestContext, controllerName);

    try  
   {
        controller.Execute(RequestContext);
    }
    finally   
    {
        factory.ReleaseController(controller);
    }
  }
---------------------------------------------------------------------------------------------------


3. Controller
Here the Controller receives request and works with the Model to prepare data needed by the View. All controller classes inherit from a base System.Web.Mvc.Controller.


In this case, a SalesController controller is invoking the Index Action method. The SalesController is responsible for generating the response to the browser request. For example, it may return a particular view back to the browser or redirect to another controller.

The MVCHandler uses the IControllerFactory instance and tries to get IController instance. If successful, then Execute() method builds a list of parameters from the request context and get called, next passed this parameter to action method of controller.
---------------------------------------------------------------------------------------------------
protected void Application_Start()
{
   AreaRegistration.RegisterAllAreas();
   ControllerBuilder.Current.SetControllerFactory(new     CustomControllerFactory());
}
---------------------------------------------------------------------------------------------------
The IControllerFactory could be the default controller factory or a custom factory initialized at the Application_Start ().


4. Action Execution
The Controller class is inherited from the ControllerBase, the ControllerActionInvoker object is associated with a controller object. It identifies which action method is called and invokes it. Action to be executed is chosen based on attributes ActionNameSelectorAttribute and ActionMethodSelectoreAttribute. The ActionNameSelectorAttribute helps to select the correct method, if more than one action method is found which has the same name, action filters are applied to invoke the correct one. Action filter is an attribute that can be applied on action method or an entire controller.

There are four types of MVC filters, AuthorizationFilters, ExceptionFilters, ActionFilters and ResultFilters. Action invoker uses a Model Binder object in case action method has argument(s).  A Model Binder converts a HTTP Request into an object and pass it to the Action method.


5. View Result
The action method gets the inputs and prepares appropriate response data and then executes the result by returning result type. The View Result is used to process view and also responsible for selecting and involving the appropriate View Engine to render the resulting response in html form.

MVC supports many action result return types; the top is the ActionResult which is a base class and it has ViewResult, PartialViewResult, EmptyResult, RedirectResult, RedirectToRouteResult, JsonResult, JavaScriptResult, ContentResult, FileContentResult, FileStreamResult, FilePathResult subtypes.


6. View Engine
The Execution of View Result involves selection of the appropriate View Engine to render the View Result in the browser. It is handled by IViewEngine interface of the view engine. There are four View Engines (Razor, ASPX, Spark and NHaml) supported by MVC and it has different syntax to implement the view, Razor View engine used .cshtml and .vbhtml, While Web Form View Engine used .aspx to design the layout of the user interface.
---------------------------------------------------------------------------------------------------
protected void Application_Start()
{
      ViewEngines.Engines.Clear();

    ViewEngines.Engines.Add(new MyCustomViewEngine());
  }
---------------------------------------------------------------------------------------------------Developer can also register own custom view engine to Asp.Net MVC application from Application_Start ().


7. View
Views are responsible for generating HTML in the MVC framework, they query on model for data and build HTML from it. An Action method may return a simple string, a binary file, JSON formatted data or file depends on Action result. Commonly an Action Methods returns a ViewResult which rendered as an HTML page to the browser using the current View Engine.

About Author:
Mahesh Deore  is enthusiast .net developer who works as associate consultant with Systems Plus Pvt. Ltd. He in free time reads and write on various web technologies. He can be contacted at: mahesh.d@spluspl.com

7 comments: