Exploring the Global.asax file in ASP.NET

Posted by: Suprotim Agarwal , on 3/15/2008, in Category ASP.NET
Views: 204915
Abstract: 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.
Exploring the Global.asax file in ASP.NET
 
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().
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.
If you liked the article,  Subscribe to my RSS Feed or Subscribe Via Email 
 
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by MURALI KRISHNA on Tuesday, June 10, 2008 2:18 AM
HAI THIS IS MURALI.GOOD ARTICLE.
Comment posted by chow on Tuesday, September 23, 2008 1:09 AM
Good one mate
Comment posted by Vijay Gonela on Tuesday, December 2, 2008 1:00 AM
This is one of the best article I found
related to Global.asax... explained in simple terms
Thank u
Comment posted by Shakti SIngh Dulawat on Friday, January 9, 2009 3:09 AM
This is very nice example mention my you, this is helpful for programming logic.
Thanks
Shakti
<strong><a href="http://www.nextmvp.blogspot.com/" >www.nextmvp.blogspot.com</a></strong>
Comment posted by Thanigainathan on Friday, January 9, 2009 4:55 AM
Hi,

This article is nice. But have not mentioned any specific usage of Global.asax in page level.
Please give some example in that.

Thanks,
Thani
Comment posted by Song on Friday, January 9, 2009 12:16 PM
example is good, but if show how to show on .aspx page the err, it were more better
Comment posted by srikanth on Friday, January 9, 2009 4:32 PM
I think app_error will not be called if u install your app on IIS and if any un-handled exception is called...
this is what i am experiencing right now in my app.
can you confirm whether app_error in global.asax is called if i install it on IIS???
mine is asp.net 2.0 app
Comment posted by Jigar on Monday, January 12, 2009 1:04 AM
This is a good article but there is no option on the page to print this article as it is.
Comment posted by vineet kumar on Tuesday, April 7, 2009 1:55 AM
This is a good article regarding global.asax.
i have searched a lot about this file and its events, but hardly get something usefull. Can u please tell me how to use response.redirect() method in global.asax file. Can we use javascript in this file. Actually i want the reference of the current httprequest in global.asax whenever any event of this file is fired. Can u tell me that whether its possible or not. Thanks
Comment posted by Waqar Ahmad on Wednesday, May 13, 2009 3:10 AM
Great Article thanx
Comment posted by Adam on Friday, September 11, 2009 4:55 PM
this article is very nice but we need to more examples to handel it
Comment posted by satish on Monday, November 9, 2009 10:45 AM
It's good Articles , but something is missed, over all that good statement

thanks

satish

india
Comment posted by ram on Friday, December 4, 2009 11:25 PM
thanks
Comment posted by Abhishek Shukla on Thursday, December 17, 2009 10:34 AM
Nice Work.
Comment posted by Prasant on Friday, December 18, 2009 6:09 PM
This Is The Best Article, Thank you..
Comment posted by Kamalesh Sengaonkar on Wednesday, March 17, 2010 7:16 AM
It's good Articles . Really Helped
Comment posted by Anandan Velayudham on Thursday, April 8, 2010 1:39 AM
thanks a lot...this article is very nice....
Comment posted by reza on Thursday, April 8, 2010 6:26 PM
I really appropriate about your article & for spend your time to direct us into a simple and clear way to understand the concept and implementation of Global.asax.
Comment posted by Ravi on Wednesday, July 28, 2010 5:50 AM
Nice article, explains required related details in simpler manner.
Comment posted by Joysing on Tuesday, August 24, 2010 3:21 AM
The articles given in your website are very helpful to me and my friends. Thanks alot
Comment posted by hi on Wednesday, October 6, 2010 5:50 AM
fhgfdh
Comment posted by Subhabrata Bose on Saturday, January 15, 2011 9:47 AM
Hey man....
This is the best article till now i have seen about global.asax, described in quite a simple way..
but can you please tell me where can i get much more advanced infor about this global fine.
Comment posted by prajakta on Friday, March 4, 2011 7:11 AM
Nice article.
But I have one question : When I browse my application, Application_BeginRequest() event will get fired. But what if I close the browser itself? None of the event is fired in this case. In this case when the Session_End() event will get fired?

Thanks.
Comment posted by billu on Monday, March 21, 2011 3:12 AM
example not enough
Comment posted by Perumal on Monday, July 18, 2011 9:53 AM
Simple & Clear explanations.
thanks suprotim
Comment posted by hi on Monday, December 12, 2011 6:12 AM
fhgfdh
Comment posted by s on Tuesday, April 24, 2012 4:03 AM
s
Comment posted by remo on Thursday, May 10, 2012 6:09 AM
Very good example...
Comment posted by kumar on Tuesday, June 12, 2012 4:42 AM
nice post
Comment posted by mike on Tuesday, June 12, 2012 4:43 AM
you may like this post:
http://webgeek.elletis.com/how-to-create-global-functions-in-asp-net-4-0/
Comment posted by Vijay on Thursday, August 29, 2013 4:02 AM
Informative.. Thanks for the post.. :)

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel