Monday, April 13, 2009

Code-behind file for Global.asax

I like the code-behind file pattern that is used for the aspx files in an ASP.Net web-site as it allows me to separate the code from the presentation. But for some reason when you try and add the global.asax file (that contains the Global Application class) to a website, Visual Studio does not give you the option to create a code behind file (The most probable reason for this is that the asax file unlike the aspx, is not used to present a UI to the user).

Here are some steps that you can take so that you can move your code-logic to a code-behind file linked to the global.asax file:

1. Add the global.asax file to your website.

2. Add a new class and name it global.asax.cs. (If you are using VB, then name it global.asax.vb). Visual Studio might inform you that it is a class file type and that it should be added to App_Code folder. Answer Yes.


3. Extend the newly added global class by making it inherit from “System.Web.HttpApplication


4. Move all the code that appears between the <script runat=”server”>……</script> tags to the “global.asax.cs” file.


5. Delete the <script runat=”server”></script> tag from the asax file.

6. Modify the application directive in the asax file from

<%@ Application Language="C#" %>


<%@ Application Language="C#" CodeBehind="~/App_Code/global.asax.cs" Inherits="global" %>

7. Test the modification by dropping a break-point on the first line of the “Application_Start” method. Run the web-site. If everything you did was correct – the break-point should be hit as soon as your web-site starts.


If you are doing this for a VB ASP.Net application, then you need to name your class as [global], because “global” is a key-word in VB.



Anonymous said...

Thank you for this clear and concise example.

Doug Kirschman said...

Thanks for the post. You may want to add that, if one has VB as thelanguate, they must name the class file Global_asax because Global is a keyword in VB.

Doug Kirschman said...

Disregard that... I saw the note at the bottom of the page to use [] around name.

sridhar said...

i followed u r article.but whn i create a cs file manually and write my desired code ..this global.asax is not accessing the global.asax.cs file..can u suggest the reason..and solution.