ASP.NET MVC Life Cycle

From getting client request to sending a response, the Asp.NET MVC lifecycle is bit complex. This lifecycle is totally different from old Asp.NET Webforms. As the page in Webforms has page lifecycle many people compare this with Asp.NET MVC lifecycle which is totally a different thing.

The thing is Asp.NET MVC and Webforms are both implemented using HttpHandlers over Asp.NET and the way they respond to request is different based on their implementation. Usually in Webforms the url points to aspx page which get processed and generate response. However, MVC is bit indirect in this process. In MVC, url gets routed to specific controller and action methods to generate a response.

This article introduces Request Life Cycle and Application Events that takes place as the request travel through MVC framework and Asp.NET platform. It also explains different methods to interact with this events. Let’s get started.

Contents

MVC Request Life Cycle

Before we start discussing the life cycle, let’s briefly understand the concept of HttpHandlers and HttpModules.

Handlers are responsible for generating the actual response in MVC. They implement the IHttpHandler class and only one handler will execute per request. On the other hand, HttpModules are created in response to life cycle events. Modules can, for example, be used for populating HttpContext objects. A request can use many modules. These classes derive from IHttpModule.

Now,

The thing is these HttpModules and HttpHandlers are the entry points to the ASP.NET MVC framework. Requests to an ASP.NET MVC-based Web application first pass through the UrlRoutingModule object, which is an HttpModule. This module parses the request and performs route selection.

From the selected Route object, the UrlRoutingModule object obtains the IRouteHandler object that is associated with the Route object. Typically, in an MVC application, this will be an instance of MvcRouteHandler.

The IRouteHandler instance creates an IHttpHandler object and passes it the IHttpContext object. By default, the IHttpHandler instance for MVC is the MvcHandler object. The MvcHandler object then selects the controller that will ultimately handle the request.

You can download a PDF document from here that charts the lifecycle of every ASP.NET MVC 5 application, from receiving the HTTP request to sending the HTTP response back to the client.

Http Application Class

The MVCApplication class in Global.asax file inherits HttpApplication class.

1 public class MvcApplication : System.Web.HttpApplication

HttpApplication Class defines the methods, properties, and events that are common to all application objects in an ASP.NET application. This class is the base class for applications defined by the user in the Global.asax file.

HttpApplication class has number of application and request level events which you can override.

 1 public class MvcApplication : System.Web.HttpApplication
 2 {
 3 
 4     protected void Application_Start(object sender, EventArgs e)
 5     {
 6     }
 7 
 8     protected void Application_BeginRequest(object sender, EventArgs e)
 9     {        
10     }
11 
12     protected void Application_EndRequest(Object sender, EventArgs e)
13     {
14     }
15 
16     protected void Application_Error(object sender, EventArgs e)
17     {
18     }
19 
20     protected void Application_End(object sender, EventArgs e)
21     {
22     }
23 
24 }

Below is a complete list of events you can override in HttpApplication class.

Global.asax Events

  • Application_Init: Fired when an application initializes or is first called. It is invoked for all HttpApplication object instances.

  • Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.

  • Application_Error: Fired when an unhandled exception is encountered within the application.

  • Application_Start: Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.

  • Application_End: Fired when the last instance of an HttpApplication class is destroyed. It is fired only once during an application’s lifetime.

  • Application_BeginRequest: Fired when an application request is received. It is the first event fired for a request, which is often a page request (URL) that a user enters.

  • Application_EndRequest: The last event fired for an application request.

  • Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.

  • Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework has finished executing an event handler.

  • Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).

  • Application_PreSendContent: Fired before the ASP.NET page framework send content to a requesting client (browser).

  • Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.

  • Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.

  • Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.

  • Application_UpdateRequestCache: Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.

  • Application_AuthenticateRequest: Fired when the security module has established the current user’s identity as valid. At this point, the user’s credentials have been validated.

  • Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.

  • Session_Start: Fired when a new user visits the application Web site.

  • Session_End: Fired when a user’s session times out, ends, or they leave the application Web site.

PreApplicationStart Method

MVC Request lifecycle contains events like Appliication Start and Application End which we can configure in Global.asax file.

However,

We sometimes need to execute some custom code before all this events take place in the first place, like registering a HttpModule. In that case we can use PreApplicationStart method to register this HttpModules.

The PreApplicationStart method is defined at the assembly level using an attribute. We can define the name of a type as well as a method on that type that we want to run before our application starts. Below is the example,

1 [assembly: PreApplicationStartMethod(typeof(PreApplicationStart), "Start")]

Working with Events Across Frameworks Using HttpModules

As I mentioned earlier both Webforms and MVC frameworks uses HttpModule and HttpHandler for their request and response pipeline. We are interested in HttpModule here. We can set any number of HttpModules in an ASP.NET Http request and response pipeline.

One of the greatest feature of ASP.Net Application Life Cycle that its events can be accessed across frameworks. ASP.NET application whether it’s built on MVC or not. In fact, we can have two applications running side by side using different frameworks and still leverage the same life cycle events.

For example, you could have a webforms application and an MVC application running side by side. You could then build an HttpModule to hook into the same life cycle events for both and perform some common tasks.

Below is a sample code for a HttpModule that registers for HttpApplication events using event handlers.

 1 public class HelloWorldModule : IHttpModule
 2 {
 3     public HelloWorldModule()
 4     {
 5     }
 6 
 7     // In the Init function, register for HttpApplication 
 8     // events by adding your handlers.
 9     public void Init(HttpApplication application)
10     {
11         application.BeginRequest += 
12             (new EventHandler(this.Application_BeginRequest));
13         application.EndRequest += 
14             (new EventHandler(this.Application_EndRequest));
15     }
16 
17     private void Application_BeginRequest(Object source, EventArgs e)
18     {
19    
20     }
21 
22     private void Application_EndRequest(Object source, EventArgs e)
23     {
24         
25     }
26 }

Further Reading

References

ASP.NET MVC Life Cycle
Share this

Subscribe to Code with Shadman