Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Working with the ASP.NET Global.asax file

Posted by Ravi Varma Thumati on January 23, 2009

The Global.asax file, sometimes called the ASP.NET application file, provides a way to respond to application or module level events in one central location. You can use this file to implement application security, as well as other tasks. Let’s take a closer look at how you may use it in your application development efforts.

Overview

The Global.asax file is in the root application directory. While Visual Studio .NET automatically inserts it in all new ASP.NET projects, it’s actually an optional file. It’s okay to delete it—if you aren’t using it. The .asax file extension signals that it’s an application file rather than an ASP.NET file that uses aspx.

The Global.asax file is configured so that any direct HTTP request (via URL) is rejected automatically, so users cannot download or view its contents. The ASP.NET page framework recognizes automatically any changes that are made to the Global.asax file. The framework reboots the application, which includes closing all browser sessions, flushes all state information, and restarts the application domain.

Programming

The Global.asax file, which is derived from the HttpApplication class, maintains a pool of HttpApplication objects, and assigns them to applications as needed. The Global.asax file contains the following events:

  • Application_Init: Fired when an application initializes or is first called. It’s 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’s fired only once during an application’s lifetime.
  • Application_BeginRequest: Fired when an application request is received. It’s 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 is 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 sends 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.

The event list may seem daunting, but it can be useful in various circumstances.

A key issue with taking advantage of the events is knowing the order in which they’re triggered. The Application_Init and Application_Start events are fired once when the application is first started. Likewise, the Application_Disposed and Application_End are only fired once when the application terminates. In addition, the session-based events (Session_Start and Session_End) are only used when users enter and leave the site. The remaining events deal with application requests, and they’re triggered in the following order:

  • Application_BeginRequest
  • Application_AuthenticateRequest
  • Application_AuthorizeRequest
  • Application_ResolveRequestCache
  • Application_AcquireRequestState
  • Application_PreRequestHandlerExecute
  • Application_PreSendRequestHeaders
  • Application_PreSendRequestContent
  • <<code is executed>>
  • Application_PostRequestHandlerExecute
  • Application_ReleaseRequestState
  • Application_UpdateRequestCache
  • Application_EndRequest

A common use of some of these events is security. The following C# example demonstrates various Global.asax events with the Application_Authenticate event used to facilitate forms-based authentication via a cookie. In addition, the Application_Start event populates an application variable, while Session_Start populates a session variable. The Application_Error event displays a simple message stating an error has occurred.

protected void Application_Start(Object sender, EventArgs e) {
Application[“Title”] = “Builder.com Sample”;
}
protected void Session_Start(Object sender, EventArgs e) {
Session[“startValue”] = 0;
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if(null == authCookie) {
// There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try {
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
} catch(Exception ex) {
// Log exception details (omitted for simplicity)
return;
}
if (null == authTicket) {
// Cookie failed to decrypt.
return;
}
// When the ticket was created, the UserData property was assigned
// a pipe delimited string of role names.
string[2] roles
roles[0] = “One”
roles[1] = “Two”
// Create an Identity object
FormsIdentity id = new FormsIdentity( authTicket );
// This principal will flow throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, roles);
// Attach the new principal object to the current HttpContext object
Context.User = principal;
}
protected void Application_Error(Object sender, EventArgs e) {
Response.Write(“Error encountered.”);
}

This example provides a peek at the usefulness of the events contained in the Global.asax file; it’s important to realize that these events are related to the entire application. Consequently, any methods placed in it are available through the application’s code, hence the Global name.

Here’s the VB.NET equivalent of the previous code:

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application(“Title”) = “Builder.com Sample”
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Session(“startValue”) = 0
End Sub
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As
 EventArgs)
‘ Extract the forms authentication cookie
Dim cookieName As String
cookieName = FormsAuthentication.FormsCookieName
Dim authCookie As HttpCookie
authCookie = Context.Request.Cookies(cookieName)
If (authCookie Is Nothing) Then
‘ There is no authentication cookie.
Return
End If
Dim authTicket As FormsAuthenticationTicket
authTicket = Nothing
Try
authTicket = FormsAuthentication.Decrypt(authCookie.Value)
Catch ex As Exception
‘ Log exception details (omitted for simplicity)
Return
End Try
Dim roles(2) As String
roles(0) = “One”
roles(1) = “Two”
Dim id As FormsIdentity
id = New FormsIdentity(authTicket)
Dim principal As GenericPrincipal
principal = New GenericPrincipal(id, roles)
‘ Attach the new principal object to the current HttpContext object
Context.User = principal
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Response.Write(“Error encountered.”)
End Sub

A good resource

The Global.asax file is the central point for ASP.NET applications. It provides numerous events to handle various application-wide tasks such as user authentication, application start up, and dealing with user sessions. You should be familiar with this optional file to build robust ASP.NET-based applications.

 

Advertisements

11 Responses to “Working with the ASP.NET Global.asax file”

  1. sailu said

    sir,
    notes is good but who dont know the concepts , i mean screens how could they can understand. so please if there is possible put some screens when the time tipical cases..expect this every thing is excelent..

    • ravivarmathumati said

      Hello Sailu,

      Thank you for the update, i am also trying to put some images so that it will be more visilible for the users to understand the concepts. It is little bit hard here to put both document and images in a single post. we have to add the images separatly for the posts. Let me find some ways to give you clear explanation with some images.

      Keep on posting comments…
      …….. Ravi Varma Thumati

  2. sir,
    blog notes is too good but we are confused, where it was available Gloabal.asx file..we can understand what you are telling from this blog, but please put some screens for clarification… i read some where
    may i know
    What is a satellite assembly?

  3. praveena said

    sir,
    iam in different domain, i was join in .Net classes but there is no sufficiant notes, but here good notes in your we have some doubts in asp.net
    that is Application,Session, and Cookies.. which purpose..thease are used?

    • ravivarmathumati said

      Hello Praveena,

      Good evening.. Application, Session and Cookies all these concepts are used for maintaining the state of the page or control.

      For example you have two web pages one is Login.aspx and another one is homepage.aspx. you will provide username and password into login page and if you are a valid user you will be redirected to homepage.aspx. you want to display the username in homepage.aspx after a successful entry, but here the problem is username information was provided in your login.aspx only so it cannot be used in homepage.aspx. to use that information you have to pass that username from your login page to homapage. That passing values from one page to another page can be done in asp.net by means of State Management.. goto State Management in asp.net article for clear understanding.

      Ravi Varma

  4. santhisri said

    hai sir,
    verygood sites in .net notes is very usefull
    very thankfull sir,but we are taking so much time for topic searching and also we are confused which topic later will which topic
    so please put atleast contents headding or please put Indexing..

  5. swpna said

    Respected Sir,

    I have querry on openings. Right now im a student ece, i came to know regarding the openings(value labs etc..). After completing my course how do i get the information regarding the openings
    Waiting for ur reply..
    Thanking u,
    Swapna

  6. prethi said

    sir,
    your blog has good notes, iam a student of BioTech, i have interested in IT so came to learn .Net concepts and i was join one institute
    teaching is good but we are not able to understand like
    i have one problem with my pc. when i open IIS in settings
    it opens but there is no tree to expand on left hand side. sir plz kindly tell me what was the problem in it.
    and how to execute my with my IIS and without IIS?

    • ravivarmathumati said

      Hello Prethi,

      Thank you very much for your interest in this blog. Look like you IIS is not properly installed. To test you IIS just goto IE browser and in address bar type http://localhost/ and press enter, if you get two windows then your IIS is working fine otherwise check the services also, there will a service called world wide web publishing service should be running. If all these conditions fails try to install IIS once again.

      ……..Ravi Varma Thumati

  7. satya sri said

    goodmorng sir!
    i am very happy about ur spoon feading of .net classes
    the way of ur enterg into topic is too good
    why its came?

  8. Michal Yao said

    Useful info. Lucky me I found your website by chance, and I’m stunned why this accident didn’t came about earlier! I bookmarked it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: