Under some circumstances (typically application start up and shut down) I would get the following “Session state is not available in this context” error within the Global.asax event: “Application_PostAcquireRequestState” whenever I tried to access the Session object.
According to the documentation: “The PostAcquireRequestState event is raised after the AcquireRequestState event has occurred.” And the AcquireRequestState documentation states: “Occurs when ASP.NET acquires the current state (for example, session state) that is associated with the current request.”
So I am not sure why the Session object was not available in the PostAcquireRequestStateMethod. The simple way around this issue is to wrap the access to Session state object in a try catch block and forget about it. But it bothered me, because I had the debugger set to break at all exceptions. So I wanted to find a better way.
And the better way is to wrap your access to the Session state object in the following if statement:
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState) {….}
Not sure exactly why the method gets called multiple times, but by making sure the ContextHandler needs the session state object, we can be sure that the session state object is available – as our access is from the PostAcquireRequestStateMethod event.
Reference:
http://msdn.microsoft.com/en-us/library/system.web.httpapplication.acquirerequeststate.aspx
http://msdn.microsoft.com/en-us/library/system.web.httpapplication.postacquirerequeststate.aspx
2 comments:
Thanks for posting this, I had the same problem and was equally mystified. Your workaround was nicer than what I had done originally.
I think know why it's getting called multiple times. At least if it's a web page.
The initial page request (aspx file or similar) requires a session, so it has it.
After that initial page load, other requests will be made to the server. These will be for such things as css files, images, and other things that the web server knows are session-less.
Being that there is no point loading a state for them, the server doesn't load a session for those requests.
Post a Comment