Wednesday 20 May 2015

Page life cycle in MVC in asp.net

Here we will learn Asp.net MVC life cycle.
Asp.net MVC Life Cycle totally different with web application life cycle, In asp.net MVC does not contain any event alike web form contain ex.pre Render, oninit etc.
Here whenever we put request for a URL the only thing which happen here is that some controller action is called and response render to the browser.
Asp.Net MVC Life Cycle :
The following diagram shown the MVC life cycle.


1.   Routing:
          Routing in MVC is nothing but matching incoming request (URI) with action. The mvc request is work on basis of the routing data which exists in Route Table. At the first time request is empty means first request of the application route table is empty. Application start event fill the required routes depending on the  URL which is used by the client browser “UrlRoutingModule” uses route table to retrieve correct data of route table for defining which controller and action should accureS.

1.   If UrlRoutingModule gets correct RouteData, it creates RequestContext object which represent current HttpContext and RouteData. Routing engine forwards the RequestContext object to corresponding IRouteHandler
If UrlRoutingModule does not get matching controller and its action for incoming request it returns HTTP status code 404 (Page not found).
Below example shows how you can create mapping of routes in RegisterRoutes method called from Application Start Event.
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default"
        , "{controller}/{action}/{id}"
        , new { controller = "Security",
                action = "Login", id = UrlParameter.Optional }               
    );
}
           
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); specifies any request for .axd should be ignored and should not process.
routes.Maproute specifies route name as default and matching request should be forward toSecurity controller and Login method.
For each mapping Route name should be unique. You can remove particular route byRouteTable.Routes.Remove(“route item”) method. See more about ASP.NET MVC routing with example

2.   IRouteHandler Interface
It exposes a single method GetHttpHandler, which provides RouteHandler class instance based on RouteContext data to process request. All Routes which are added to RouteTable by MapRoute extension method are handled by default RouteHandler that is MvcRouteHandler class defined in the System.Web.Mvc namespace.
Below is interface definition
public interface IRouteHandler
{
    IHttpHandler GetHttpHandler(RequestContext requestContext);
}           
           
3.   MVCHandler
MvcHandler is responsible for initiate actual processing of ongoing request and generate response. MvcHandler gets information of current request through RequestContext object passed to its constructor.
Below is the constructor code for MVChandler
public MvcHandler(RequestContext requestContext)
{
}
           
MvcHandler class implements three interfaces : IHttpAsyncHandler, IHttpHandler and IRequiresSessionState. IHTTPHandler's ProcessRequest method actually process the ongoing request.
The ProcessRequest method is implemented in MvcHandler as below
protected internal virtual
         void ProcessRequest(HttpContextBase httpContext)
{
    SecurityUtil.ProcessInApplicationTrust(delegate {
        IController controller;
        IControllerFactory factory;
        this.ProcessRequestInit(httpContext, out controller, out factory);
        try
        {
            controller.Execute(this.RequestContext);
        }
        finally
        {
            factory.ReleaseController(controller);
        }
        });
}

           
4.   The Controller Executes
MvcHandler uses IControllerFactory instance and to get IController object. All Mvc controllers implement IController interface. This interface has Execute method which actually execute your action method code. So Mvc Controller executes method from IController interface.
At the beginning of Execute method it creates TempData object. The Execute method get Action from RouteData based on ongoing request. Then MVC Controller callControllerActionInvoker 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.
5.   Action Execution
After the particular controller gets instantiated ActionInvoker determines which specific Action method needs to be execute. ActionInvoker uses ActionNameSelectorAttribute and ActionMethodSelectorAttribute to select Action method for execution. 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.
6.   ViewEngine
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 develop Views. You can also create your own ViewEngines and use it. For performance reason it is better to remove ViewEngines which are not required. Below code clear all ViewEnginees and register only Razor
protected void Application_Start()
{
    //Remove All Engine
    ViewEngines.Engines.Clear();

    //Add Razor Engine
    ViewEngines.Engines.Add(new RazorViewEngine());
}
 
7.   Render View Result
Action method can return a simple string value, binary file, JSON data or JavaScript block. And the most important is ViewResult. 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 prepare response for current request.
For each Action method controller executes either RedirectToAction or RenderViewmethod. The RenderView method uses a class named ViewLocator to find corresponding View to render.
Then If there is MasterPage or ViewData then it get set appropriately and finally the RenderView method get called on ViewPage.
In Short we will learn page life cycle:
Basically, there is no page life cycle per se (because there is no 'page' object), but there is a request processing pipeline, which usually goes something like this:
1.   Incoming request is picked up by the System.Web.Routing.UrlRoutingModule which uses the request url to map the request to a controller action method.
2.   The appropriate controller is instantiated
3.   The OnActionExecuting-methods of action filters on the controller and/or action are invoked
4.   Model binding and input validation may occur
5.   The action method itself is invoked
6.   Any OnActionExecuted and OnResultExecuting-methods of action filters are invoked
7.   The ActionResult returned by the action method (typically, a ViewResult which renders HTML) is executed.
8.   Any OnResultExecuted-methods of action filters are invoked.

No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...