"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!

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

Left by Tyre at 7/21/2009 7:36 AM
Gravatar
Thanks a lot Ben, finally i can use the web develop server of vs2008. With the other solution that I taked from MS was impossible..

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

Left by Grant at 7/30/2009 5:54 AM
Gravatar
Im getting the same error guys. And seriously need some help. Been stuck on this issue for the last two days now.

This is my situation:

I added a new page to a website which I am maintaining. The page has a user control on it. and on the user control it has a ListView displaying a few records.

For some odd reason, when i set the start page to this new page i get this error Session state is not available in this context. Im totally dumstruck been googling this like crazy but nothing....PLEASE HELP.....

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

Left by Benjamin Day at 7/30/2009 6:58 AM
Gravatar
Grant,

So are you saying that you're getting this error but you don't have any references to the Session object?

Can you post your exception with a stack trace?

-Ben

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

Left by Grant at 7/30/2009 7:10 AM
Gravatar
Hi Ben,

Here is the exception detail:
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 MFS.FundOfFunds.Web.Global.Application_Error(Object sender, EventArgs e) in C:\Projects\MFS.FundOfFunds\MFS.FundOfFunds.Web\Global.asax.cs:line 42
at System.EventHandler.Invoke(Object sender, EventArgs e)
at System.Web.HttpApplication.RaiseOnError()
InnerException:


Im totally lost on this one..im relatively new to .Net but trying really hard here....Please let me know

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

Left by Grant at 7/30/2009 7:36 AM
Gravatar
Hi Ben,

Yes im not referencing any session objects...the error is raised in the following method:

protected void Application_Error(object sender, EventArgs e)
{
// Get the last exception that has occurred
Exception ex = Server.GetLastError().GetBaseException();
// You can perform logging here // Store it in the session
// Redirect to Error page Server.Transfer("Error.aspx");
LoggingHelper.LogEntry(CustomLogger.Web, ex.Message, ex, LogLevel.Error);
Session["ExceptionDetail"] = ex;
Server.Transfer(NavigationHelper.GetUrl(InternalPage.LandingPage));

}

It doesnt even hit any of my methods in the page that i have set as my start page. What is weird is that when i remove the user control from the aspx page..and set that page as my start page then it doesnt give me any errors...but the second i put the user control back in that page and set that page as the start page then it bombs out with that error.

Please help.

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

Left by Benjamin Day at 7/30/2009 7:42 AM
Gravatar
I haven't tried to compile this but try this out. The important part is the "if" block that looks at Context.Handler.

-Ben

protected void Application_Error(object sender, EventArgs e)
{
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
// Get the last exception that has occurred
Exception ex = Server.GetLastError().GetBaseException();
// You can perform logging here // Store it in the session
// Redirect to Error page Server.Transfer("Error.aspx");
LoggingHelper.LogEntry(CustomLogger.Web, ex.Message, ex, LogLevel.Error);
Session["ExceptionDetail"] = ex;
Server.Transfer(NavigationHelper.GetUrl(InternalPage.LandingPage));
}
}

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

Left by Benjamin Day at 7/30/2009 7:44 AM
Gravatar
Just to be clear on why the "if" block is important, you're hitting the
Session["ExceptionDetail"]=ex; line and there's no session there because of whatever the current http handler is doesn't have session enabled.

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

Left by Grant at 7/30/2009 7:47 AM
Gravatar
Yes you right.

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

Left by Grant at 7/30/2009 8:12 AM
Gravatar
Ok that got rid of that session state error..but now im getting the following:

Server Error in '/MFS.FundOfFunds.Web' Application.
--------------------------------------------------------------------------------

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0123: No overload for 'ListViewRejectListReport_ItemDataBound' matches delegate 'System.EventHandler<System.Web.UI.WebControls.ListViewItemEventArgs>'

Source Error:



Line 15: <td>
Line 16: <div id="SearchResultsGrid" style="overflow: auto; height: 300px" runat="server">
Line 17: <asp:ListView ID="ListViewRejectListReport" runat="server" OnItemDataBound="ListViewRejectListReport_ItemDataBound"
Line 18: Style="overflow: auto; height: 300px">
Line 19: <LayoutTemplate>


Source File: c:\Projects\MFS.FundOfFunds\MFS.FundOfFunds.Web\Rejected\Controls\RejectedPriceControl.ascx Line: 17


Have any ideas off the top of your head...im gona do some debugging in the meantime...Thanks so much

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

Left by Benjamin Day at 7/30/2009 8:36 AM
Gravatar
Grant,

This was the real cause of your problems. There's something wrong with your user control's code.

Specifically, there's something messed up with this attribute in your user control definition.
OnItemDataBound="ListViewRejectListReport_ItemDataBound".

You might want to try removing that attribute, and assuming that you meant to hook in to the OnItemDataBound event, go to the events section of the Properties dialog and re-create the OnItemDataBound event handler.

-Ben

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

Left by Grant at 7/30/2009 8:42 AM
Gravatar
Ben you are so the man. Thanks dude. You solved my problem...I owe u a six pack...lol

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

Left by Deb at 12/12/2009 4:27 AM
Gravatar
Has anyone told you that you are a Genius!!!

I was just going mad over why the code did not work when I uploaded it into my server. It worked fine in my dev.
And your solution worked perfect.
Thanks a LOT

Deb.

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

Left by Greg at 1/11/2010 1:10 PM
Gravatar
Thanks Ben, this sent me in the right direction for a similar issue. Wondering about this line though

"if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState) "

Why check if the context handler is read only session? and then write to the session? That would probably fail but just never happens. Could probably re-write just as this:

"if (Context.Handler is IRequiresSessionState) "

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

Left by rachmann at 6/16/2010 11:21 AM
Gravatar
Watch out for:

Server.GetLastError().GetBaseException();

You code may land in Application_Error and Server.GetLastError() may result in null! Thus the assumption that GetBaseException can always be called is wrong. Test var set to Server.GetLastError() first, then test for null prior to GetBaseException

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

Left by ER at 9/1/2010 10:01 AM
Gravatar
Thanks for your explanation, it really saved me tons of time!

Your comment:



 (will not be displayed)


 
 
 
Please add 7 and 3 and type the answer here:
 

Live Comment Preview:

 
«September»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789