Thursday, February 5, 2009

Working with the ASP.NET Global.asax file

Have you ever felt the need of writing logic at the application level; precisely a location or a file where you could handle events or errors at the application level? Well if yes, then enter the Global.asax. Using this file, you can define event handlers with application-wide or session-wide scope. In this article, we will explore the application and session level events exposed in the Global.asax file and how we can utilize these events in our applications.

The Global.asax, also known as the ASP.NET application file, is located in the root directory of an ASP.NET application. This file contains code that is executed in response to application-level and session-level events raised by ASP.NET or by HTTP modules. You can also define ‘objects’ with application-wide or session-wide scope in the Global.asax file. These events and objects declared in the Global.asax are applied to all resources in that web application.
Note 1: The Global.asax is an optional file. Use it only when there is a need for it.
Note 2: If a user requests the Global.asax file, the request is rejected. External users cannot view the file.
The Global.asax file is parsed and dynamically compiled by ASP.NET. You can deploy this file as an assembly in the \bin directory of an ASP.NET application.
How to create Global.asax
Adding a Global.asax to your web project is quiet simple.
Open Visual Studio 2005 or 2008 > Create a new website > Go to the Solution Explorer > Add New Item > Global Application Class > Add.
Examining the methods related to the events in Global.asax
There are 2 ‘set’ of methods that fire corresponding to the events. The first set which gets invoked on each request and the second set which does not get invoked on each request. Let us explore these methods.
Methods corresponding to events that fire on each request
Application_BeginRequest() – fired when a request for the web application comes in.
Application_AuthenticateRequest –fired just before the user credentials are authenticated. You can specify your own authentication logic over here.
Application_AuthorizeRequest() – fired on successful authentication of user’s credentials. You can use this method to give authorization rights to user.
Application_ResolveRequestCache() – fired on successful completion of an authorization request.
Application_AcquireRequestState() – fired just before the session state is retrieved for the current request.
Application_PreRequestHandlerExecute() - fired before the page framework begins before executing an event handler to handle the request.
Application_PostRequestHandlerExecute() – fired after HTTP handler has executed the request.
Application_ReleaseRequestState() – fired before current state data kept in the session collection is serialized.
Application_UpdateRequestCache() – fired before information is added to output cache of the page.
Application_EndRequest() – fired at the end of each request
Methods corresponding to events that do not fire on each request
Application_Start() – fired when the first resource is requested from the web server and the web application starts.
Session_Start() – fired when session starts on each new user requesting a page.
Application_Error() – fired when an error occurs.
Session_End() – fired when the session of a user ends.
Application_End() – fired when the web application ends.
Application_Disposed() - fired when the web application is destroyed.
Show me an example!!
Let us see an example of how to use the Global.asax to catch unhandled errors that occur at the application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:
C#
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error in: " + Request.Url.ToString() +
". Error Message:" + objErr.Message.ToString();
}
VB.NET
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()
Dim err As String = "Error in: " & Request.Url.ToString() & ". Error Message:" & objErr.Message.ToString()
End Sub


Here we make use of the Application_Error() method to capture the error using the Server.GetLastError().

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


Conclusion:
In this article, we learnt that Global.asax is a file used to declare application-level events and objects. The file is responsible for handling higher-level application events such as Application_Start, Application_End, Session_Start, Session_End, and so on. I would encourage you to explore the methods corresponding to the events and analyze the best possible methods to use them in your application, if needed.
I hope you liked the article and I thank you for viewing it

No comments:

Post a Comment