Tuesday, July 27, 2010

Expanding the Usefulness of Global.asax

I've long utilized the 'Global.asax' file to run assorted startup methods, both from an Application and Session perspective.  One limitation of this file is that you can't introduce "using" statements like you can in any normal C# file.  This forces you to prefix every method and class with its full definition.  This isn't so bad but I've reached a point where I have more complex code I need to run and have grown tired of all those prefixes.  Frankly, I think they also make the code much less readable.

To resolve this issue I found this excellent blog post by Ross Nelson which explains how to modify things.  Essentially Global.asax is altered to contain just this one line:
<%@ Application Language="C#" Inherits="Global" %>
This then lets you create a new 'Global.cs' file in which all of the previous contents of 'Global.asax' are placed.

2 comments:

  1. You can define a code behind file to Global.asax such as CodeBehind="App_Code/Global.cs" and put all your code in there which can have using statement..!

    ReplyDelete
  2. I know. That's precisely what Ross Nelson's article explains. Though I chose to just put the "Global.cs" file in the root directory.

    ReplyDelete