So you did some work in an ASP.Net web site and then you decided to or to add the Ajax extensions to it or switch to ASP.Net 3.5 or whatever and suddenly you get Ajax errors like "
Sys is undefined" or you don't see images and the css files are not loaded. And after googling like crazy and finding a zillion possible solutions you decide to enter in the browser address bar the url of the offending image, css file or even ScriptResource.axd files containing the ajax javascript and you see a beautiful ASP.Net error page displaying "
Session state is not available in this context.". Huh?
There are some reasons why this might happen, but let's examine the one that actually prompted me to write the article. Someone made a change in
global.asax, trying to work with Session there, more precisely in the
Application_AcquireRequestState event. The error was returned by the Session property of the
HttpApplication object, the one that the global.asax file represents! In fact, this error can only be thrown from there in the current ASP.Net implementations.
First mistake: there was a Session property available in the HttpApplication object and it was immediately assumed that it is the same as
Page.Session or
HttpContext.Current.Session. It is about the same, except 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! Yes, but it applies to your page, not to all the IHttpHandler implementations, like
ScriptResource.axd! Also, the css and image problems occured for me only when opening the site in Cassini, not in IIS, so maybe it opens separate threads to load those resources and ignores the session or something similar, 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, so you have to 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.