Friday, January 8, 2010

how to add a Global.asax code behind file

One of the subtle differences I've found while working with web projects in Visual Studio 2005 is the Global.asax code is placed in script tags within the actual .asax page, not a codebehind file, as it was with .NET 1.1. This article describes how to set up the Global.asax file to utilize the Global.asax.cs codebehind file.

First off, go to files->add new and select the "Global Application Class" file. You'll notice right off the bat that the option to put the code in a separate file is grayed out. Ignore this and click "Add".

Next, go back to files->add new and select a "Class" file. Type in the name "Global.asax.cs" and click "Add". Visual Studio will prompt you to add this file to the App_Code directory, select "Yes" and continue.

Now that the files are in place, we need to do some slight manipulation of the existing code to get this solution to compile.

To start, the Global class in the Global.asax.cs file needs to implement HttpApplication.

public class Global : System.Web.HttpApplication

Next, move the code within the script tags from the Global.asax file to the Global.asax.cs file -within the Global class.

void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}

...snip...

void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
}

Once the code has been moved, remove the script tags from Global.asax:



Add the following to the Application directive at the top of the same page:

CodeBehind="Global.asax.cs" Inherits="Global"

The entire contents of the Global.asax file should look like:

<%@ Application Language="C#" CodeBehind="Global.asax.cs" Inherits="Global" %>

The solution should compile and the Global events should fire correctly as well.

http://www.xerratus.com/2006/10/20/NET20GlobalasaxCodeInSeparateFile.aspx