Tuesday, August 21, 2007

Check to see if the ASP.Net session is available

HttpContext.Current.Session will return null when the session information is not available yet while HttpApplication.Session will throw an exception.

It is not uncommon to handle page errors in a Global.asax file's Application_Error event to log and notify administrators of problems with a website that were not handle. This can be used in conjunction with a custom error section of a webconfig to have a more graceful error handling as customErrors turned off is not user friendly and can often lead to security vulnerabilities.

<customErrors mode="RemoteOnly" defaultRedirect="/Error.htm">

In my Application_Error I wanted to email the equivalent of the trace's debug information which includes the session information. At first I was using the HttpApplication.Session (this.Session) property of the Global.asax class. However, that are errors (such as a 404 error) where the session is not available yet as the HttpApplication.Session will throw an exception when you try to access it. I didn't have anything that I could do with the exception so I just caught it.

I wanted to find out if there was a way to check whether the session was active so I did have to catch the exception and found out HttpContext.Current.Session returns null. I could check for null instead of catching an exception which is generally considered a better practice.