Before we begin understanding ASP.NET MVC life cycle, we should have basic knowledge of what is MVC.

ASP.NET MVC  is software design pattern to develop web applications. It  separates an application into  three logical components : Model ,View ,Controller .

a.Model  represents  data  and business logic . It maintains the data of the application.

Ex .:

public class Employee{public string EmpSal { get; set; }}

Model objects retrieve and store properties in database.

b.View is user interface. It display the data to user using model and also modify the data.

c. Controller Handles User Request.

Employee controller will handle all user inputs from employee view and update the database using Employee model and same is used by view to display data to user.

App1-min.png

As per above figure, when user requests url,it goes to the controller. Controller decides which action should be executed. It picks up the relevant view and send data to user.

If we go in deeper details in ASP.NET MVC, when the user sends a request to IIS, it validates the requested file extension & creates an application domain where the app can run. Later HttpApplication object is created once after all the HTTP object such as HttpContext, HttpRequest and HttpResponse are created. Then the request is processed by the two prominent pillars called HttpModule and HttpHandlers.

Now,Let’s see deeply into architecture.

Global.Asax File : IIS runs this file first when project executes. It is responsible for handling application & session level events.

Following are events which takes places in MVC:

  • Application_Start – fired when web application starts.
  • Application_End - fired when web application ends.
  • Session_Start - fired when user session starts for each request.
  • Session_End - fired when user session ends.
  • Application_BeginStart – fired when first  request of web application starts.
  • Application_AuthenticateStart – fired when user credentials are authenticated.
  • Application_Error – fired when error occurs.
public class MvcApplication : System.Web.HttpApplication {
 protected void Application_Start(){
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);}
}

  Areas in MVC : Areas are useful for managing web applications. Each Area has its own controller, Model & view.

mvc-area-min.png

Each area has its own AreaRegistration.cs file similar to Route.config file.

All areas are registered in Application Start event of Global.asax file :

AreaRegistration.RegisterAllAreas();

Route.Config File :

Route.Config file is entry point of web application which decides how url are mapped to controller and its appropriate actions. Controller is responsible for generating the response and sent data back to the browser(user).Each controller can handle multiple requests.

When the user requests for url, Application_Start event will get called & it will call RegisterRoutes method.It will send the collection of routes as parameter.Each route references a handler which will handle the request.

MapRoute creating a route by instantiating default MVC handler.Each RouteHandler implements interface IRouteHandler.

Every MVC Application has RouteTable.This RouteTable is responsible to map request to particular controller.

When you open RouteConfig.cs in your Project, you will see C# code as below, which is default route configuration in MVC

public class RouteConfig{   

public static void RegisterRoutes(RouteCollection routes){

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
               name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
 }
} 

When you will Build and run your Application in MVC

mvc-app-home-page.png

In this, when we run the application , by default /Home/Index method will get called.

http://localhost:62715/

http://localhost:62715/Home/Index

You can custom the route as per your need.

// Custom Route 

routes.MapRoute(
             name: "about",
             url: "Home/About",
             defaults: new { controller = "Home", action = "About", id = UrlParameter.Optional }
); 

 So for example if user hits url :  http://localhost:62715/Home/About , it will invoke Home controller  About  Action Method.

 You can manage the routes from controller using Route Attribute

 [Route("Home/ContactUs")] 
 public ActionResult ContactUs(){
       ViewBag.Message = "Your contact page.";
       return View();
}

URL Routing Module :

URL Routing module is responsible for mapping user request to particular controller actions.

As per user request, URL Routing Module will find URL in Route table to create RouteData Object.

If it finds correct match for request ,it will create RequestContext object and send request to MVCHandler.  As soon as match is found, scanning of  RouteTable  Process stops.

Depending on requested url, it will call controller’s ActionInvoker method which creates list of parameters of url request and list will be passed to controller action method to call InvokeAction  method to execute the action. Finally it will send response to user.

MVC Handler :

This class is responsible for generating response for request being processed.

It receives the information about the request from RequestContext object and passed to constructor, in implementation of GetHttpHandler() method in MVCRouteHandler class.

It implements 3 interfaces : IHttpAsyncHandler, IHttpHandler, IRequireSessionState.

Controller Execution :

MVC controller implements IController interface. It has Execute method which calls particular action

Requested by user. Execute() method gets action from RouteData based on URL.The Controller class call

ControllerActionInvoker that creates list of parameters.The parametets will be passed to respective

Controller AactionMethod gets executed.

Action Result

As we are clear that, once the ActionMethod executes our logic we will return an ActionResult, based on the type of Result it returns, View generates accordingly.

Before that we do have some ActionFilter methods which is invoked based on ActionMethod’s life cycle. Some methods are such as OnActionExecuting, OnActionExecuted etc.

Let us see some of the ActionResult types as well,

  • ViewResult : Returns a view (html type page)
  • RedirectResult : Redirects to another action method
  • ContentResult : Returns Content (user defined)
  • JsonResult : Returns a serialized JSON data

If you do not want any specific method should not accessible through public URL, you can mark that method with [NonAction] attribute.

Rendering View :

The final and tangible step in MVC life cycle is rendering the View, where the user can see what he requested and get as a response. The ViewResult one of the ActionResult generates the appropriate View to the user, by parsing the Razor syntax (cshtml) and server side codes into HTML page to the Client.

ViewResult implements the IViewEngine Interface and has some view manipulating methods such as:

  • ReleaseView : To release the View
  • FindView : Maps the appropriate View
  • FindPartialView : Returns a Partial View

Hope this article clears your basic knowledge of ASP.NET MVC life cycle architechture.