"Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

I'm doing my final preparations today for speaking at VSLive San Francisco 2008 on Wednesday and Thursday.  I went to check one of my demos and code that used to work started throwing an exception.

System.Web.HttpException was unhandled by user code
  Message="Session state is not available in this context."
  Source="System.Web"
  ErrorCode=-2147467259
  StackTrace:
       at System.Web.HttpApplication.get_Session()
       at UiDesignForTestability.WebUI.Global.InitializeMultiSessionFactoryNHibernate() in C:\code\bendaytfs2\BDC\branches\UiDesignForTestabilityMultiDb\UiDesignForTestability.WebUI\Global.asax.cs:line 24
       at UiDesignForTestability.WebUI.Global.Application_PreRequestHandlerExecute(Object sender, EventArgs e) in C:\code\bendaytfs2\BDC\branches\UiDesignForTestabilityMultiDb\UiDesignForTestability.WebUI\Global.asax.cs:line 45
       at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
       at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
  InnerException:

<ben:Panic operation="Start" intensity="Extreme" />

The offending code was trying to access the ASP.NET Session object from the PreRequestHandlerExecute event in my Global.asax.cs.  This exception shouldn't be possible.  In fact, it should be IMPOSSIBLE because according to the documentation, AquireRequestState should have fired already.  (Can you tell that I was getting anxious?  Getting on a plane tomorrow and the demos aren't working anymore.  I fixed it but I'm still anxious anyway, actually.)

Ok.  Well, it turns out that during Global.asax's processing, it fires all the events for each of the HttpHandlers in the pipeline.  Well, not all HttpHandlers implement IRequiresSessionState.  For example, System.Web.Handlers.AssemblyResourceLoader doesn't and that's what was causing the exception when InitializeMultiSessionFactoryNHibernate() was getting called. 

        protected void Session_Start(object sender, EventArgs e)
        {
            InitializeMultiSessionFactoryNHibernate();
        }

        public void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
        {
            InitializeMultiSessionFactoryNHibernate();            
        }

        private void InitializeMultiSessionFactoryNHibernate()
        {
            if (Session["NHibernateConfiguration"] == null)
            {
                Session["NHibernateConfiguration"] = "UiDesignForTestability";
            }

            SessionFacade.ConfigurationName = Session["NHibernateConfiguration"] as string;
        }

Well, back on 5/30/2006 at 2:33am, Brock Allen wrote the solution into a comment here.  The answer is to check that the current handler implements either IRequiresSessionState or IReadOnlySessionState.

        public void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
        {
            if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
            {
                InitializeMultiSessionFactoryNHibernate();           
            }           
        }

Thanks, Brock.  This helped IMMENSELY.

Now the real question is why did that code work before? 

-Ben

posted @ Monday, March 31, 2008 5:04 PM

Print

Comments on this entry:

# re: "Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

Left by charlie at 6/26/2008 1:51 PM
Gravatar
Just for Microsoft's solution sucks!

# re: "Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

Left by neeraj at 7/17/2008 8:41 AM
Gravatar
this helpe me a lot thanks saved lot of time

# re: "Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

Left by Dylan Phillips at 1/16/2009 2:20 PM
Gravatar
Brilliant! I was having this exact problem and your explanation was brilliant. I too had made the observation that my 'global.asax' method Application_AcquireRequestState was being called multiple times, but I couldn't figure out why. Thanks so much for the 'why' not just the fix!

# re: "Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

Left by Veli Pehlivanov at 1/26/2009 6:07 PM
Gravatar
10x for the solution. This helped immediately for my Senior Project.

# re: "Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

Left by Gustavo Melo at 1/27/2009 4:10 PM
Gravatar
Thx very much Ben...
Just one question, like Dylan say, why this method had a multiple calls on him?

# re: "Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

Left by Prakash Gupta at 3/21/2009 2:40 AM
Gravatar
great.......
this solved my problem.
thanx very much
Prakash Gupta

# re: "Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

Left by Mark at 5/6/2009 9:01 AM
Gravatar
Nice! Fixes a bug that kept my stylesheets and images from loading properly. DefaultHttpHandler does not implement Session.

# re: "Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

Left by Varun at 5/28/2009 7:41 AM
Gravatar
This simple code for global exception handling is giving the same problem (Session state is not available in this context.) ! Earlier it was working fine. Why ?
---
void Application_Error(object sender, System.EventArgs e)
{
Exception objError = Server.GetLastError().GetBaseException();
string strError = "Error Has Been Caught in Application_Error event \n\n\n" +
"Error in: " + Request.Url.ToString() +
"\n\n\n Error Message:" +
objError.Message.ToString() +
"\n\n\n Stack Trace:" +
objError.StackTrace.ToString();

Session["error"] = strError.ToString();

Server.Transfer("error_help.aspx");
Server.ClearError();
}

-----------
And sorry ! I couldn't implement the solution. Any kind of help will be appreciated, thanks

sood.varun82@hotmail.com

# re: "Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

Left by Ben Day at 5/28/2009 8:11 AM
Gravatar
Varun,

The error is probably coming from this line:
Session["error"] = strError.ToString();

-Ben

# re: "Session state is not available in this context" exception accessing ASP.NET Session in PreRequestHandlerExecute event

Left by Graz at 6/11/2009 4:57 AM
Gravatar
Wonderful! I was lucky enough to find this post before starting to break everything, as the code was working and it started throwing this exception all of a sudden!

Your comment:



 (will not be displayed)


 
 
 
Please add 7 and 8 and type the answer here:
 

Live Comment Preview:

 
«July»
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678