OdeToCode IC Logo

Getting Rid Of Inline Code in Global.asax (ASP.NET 2.0)

Wednesday, July 5, 2006

Q: I’m using the default web site project model in Visual Studio 2005. When I add a global.asax file to my web site, it wants me to use inline code. What do I do to get a code-behind file?

A: First, create a class that derives from HttpApplication. You'll want to override the Init event in this class. This class can live in a separate class library project, or in the App_Code directory. The class might look something like this:

using System;
using System.Web;

namespace OTC
{
    
public class Global : HttpApplication
    {
        
public override void Init()
        {
            BeginRequest +=
new EventHandler(Global_BeginRequest);
            
base.Init();
        }

        
void Global_BeginRequest(object sender, EventArgs e)
        {
            
throw new Exception("The method or operation is not implemented (yet).");
        }
    }
}

Next, add an Inherits attribute to global.asax, and point the attribute to the class we’ve just created.

<%@ Application Inherits="OTC.Global" Language="C#" %>

You now have code in a real code file. 

Before we close the post out, let me offer a word of advice:

Don’t let your HttpApplication derived class become cluttered up with a huge mess of unrelated code. Be a minimalist with global.asax code. Also, read Karl Seguin’s article “Global.asax? Use HttpModules Instead!”. HttpModules are reusable and configurable, and should be the preferred mechanism for processing most application events.