Session state is not available in this context

Who would know that HttpApplication.Session returns an null exception when the session is null, whereas HttpContext.Current.Session returns null when the session is null?

I have this ASP.NET MVC application that checks session status in Application_AcquireRequestState handler. If a session is a newly created session and a cookie containing session id has been included in the request header, the codes sign the user out (because the user’s session has expired).

The problem is that before checking whether the user’s session is a new session, I need to make sure that the session is not null. When doing this I first attempted using this.Session which is originally from base class HttpApplication.

 if (Session != null && Session.IsNewSession)

However, when later I deployed it to client’s environment I noticed that there were many Session state is not available in this context error thrown out. I also noticed an interesting thing – when Debug mode is on, the error is not being thrown out. Which is partly why I didn’t encounter this when development. However, this behavior seems not consistent – Today when I tested the same piece of code in a different environment, the same exception got thrown out only when in Debug mode.

So this issue can occur depends on the environment. What’s going on and what do we do?

The answer is – use HttpContext.Current.Session instead.

It turns out that the implementation of HttpApplication.Session will throw an exception when the session is null. So basically you cannot even check its value like what I did. According to an answer from Stackoverflow, the implementation is something like this:

[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public HttpSessionState Session
{
get
{
HttpSessionState session = null;

if (this._session != null)
{
session = this._session;
}
else if (this._context != null)
{
session = this._context.Session;
}

if (session == null)
{
throw new HttpException(SR.GetString("Session_not_available"));
}

return session;
}
}