Thursday, September 10, 2009

ASP.NET Session state is not available in the current context

I actually ran into the issue discribed in Siderite Zackwehdex's Blog: Session state is not available in the current context

An almost duplicate reprint of his article with my own specific account wired in follows ...

An ASP.Net web site that was recently switched to ASP.Net 3.5 and is suddenly returning "Sys is undefined"
Upon entering the url of the offending item into the browser address bar the ASP.Net error page displays "Session state is not available in this context.".

The reason - in global.asax - code was attempting to work with Session.
The error was returned by the Session property of the HttpApplication object, the one that the global.asax file represents!

First mistake: there was Session property available and it was immediately assumed that is the same as Page.Session or HttpContext.Current.Session. While the HttpApplication Session is nearly identical, it throws an error if the underlying Session object is null.

Ok, but why is Session null? You are a smart .Net developer and you know that the Session should be available in that event. Any documentation says so! Well, yes, but it applies to your page, not to all the IHttpHandler implementations, like the ScriptResource.axd! The css and image problems only occured for me only when seeing the site in Cassini, not in IIS, so maybe it opens separate threads to load those resources and ignores the session or something, at least at that level.

Well, how does one fix it? Adding in global.asax a condition on Session not being null throws the same error. Ok, then add it on HttpContext.Current.Session. In other words:

if (HttpContext.Current.Session!=null) //do stuff with sessions.

Maybe this problem occurs in other places as well, but only the Session property of the HttpApplication will throw the "Session state is not available in this context." error.

No comments: