Session state is not available in Global.asax AcquireRequestState and PostAcquireRequestState events
I have an ASP.NET MVC application that has per-user settings including the current culture settings. We must set Thread.CurrentThread.CurrentCulture
in events Application_AcquireRequestState
or Application_PostAcquireRequestState
HttpApplication
.
I want to maintain user settings in the session state dictionary, however, inside my method, Application_AcquireRequestState
I observe:
-
HttpContext.Current.Session == null
- QuickWatch Window Reports
this.Session
:((System.Web.HttpApplication)(this)).Session'
Threw an exception of type'System.Web.HttpException' System.Web.SessionState.HttpSessionState {System.Web.HttpException}
"Session state not available in this context".
I wonder which is HttpContext.Current._sessionStateModule == null
true even though I have it <sessionState mode="InProc" />
in my web.config file.
Why is the session unavailable?
source to share
I just ran into this problem and managed to solve it after some research. Hope this helps.
I'm not sure what you have <sessionState mode="InProc" />
in your web.config.
In my case, I need to check if my Session["Language"]
value is null in
Application_AcquireRequestState
. If it doesn't, then do some code about it. When I run my program, Application_AcquireRequestState is the first place the code will go. At this point, the session is definitely null. So if you write any session and a breakpoint goes through it, it definitely hits an error.
According to the loop, the session state will not be ready in Application_AcquireRequestState when your program starts.
Later, after my first page was executed and I set the value of my session, Application_AcquireRequestState
it will be called again and this time I have established my session. Thus, the error will not appear again.
To deal with this problem, I had the following complete code:
try
{
if (System.Web.HttpContext.Current.Session != null)
{
if (System.Web.HttpContext.Current.Session["Language"] != null)
{
lang = System.Web.HttpContext.Current.Session["Language"].ToString();
}
else
{
lang = "EN";
}
}
else
{
lang = "EN";
}
}
catch
{
lang = "EN";
}
For the code above, my default language is EN, regardless of the session state or not. Even if the code hit any session state error in the try block, my final lang value will always be "EN". I know this is a pretty nasty way of handling the code, but for my case I can avoid the session state error and ensure that the lang variable can always return a value.
Hope this helps one way or another.
source to share