Reputation: 155370
I have an ASP.NET MVC application that has per-user settings, including the current culture settings. We're supposed to set Thread.CurrentThread.CurrentCulture
within the Application_AcquireRequestState
or Application_PostAcquireRequestState
events of HttpApplication
.
I want to maintain users' settings in the Session state dictionary, however inside my Application_AcquireRequestState
method I observe:
HttpContext.Current.Session == null
this.Session
: ((System.Web.HttpApplication)(this)).Session'
threw an exception of type 'System.Web.HttpException' System.Web.SessionState.HttpSessionState {System.Web.HttpException}
"Session state is not available in this context."Interestingly, HttpContext.Current._sessionStateModule == null
true, even though I have <sessionState mode="InProc" />
in my web.config file.
Why is Session unavailable?
Upvotes: 4
Views: 2547
Reputation: 953
I just ran into this problem and manage to solve it after some studies. Hope this can help.
I'm unsure of the part where you have <sessionState mode="InProc" />
in web.config thou.
In my case, I need to check if my Session["Language"]
is null in
Application_AcquireRequestState
. If it's not, then do some code about it. When I run my program, Application_AcquireRequestState is the first place the code will go. At this point, session is definitely null. So if you are writing any session and the breakpoint stepped through it, it definitely hit the error.
According to the cycle, session state will not be ready in Application_AcquireRequestState when you run your program.
Later, after my first page executed and I had set my session value, Application_AcquireRequestState
will be called again and this time I had set my session. So the error won't appear again.
To cater for this issue, 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 session state is ready or not. Even if the code hit any session state error in the try block, my final lang value always be "EN". I know this is quite a nasty way to handle the code but for my case, I can avoid session state error and ensure that lang variable can always return a value.
Hope this somehow able to help.
Upvotes: 2