Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET session is NULL despite a IRequireSessionState/IReadOnlySessionState handler?

While looking into another problem I met a peculiar situation.

Within the Global.asax method I have the following code:

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    if (!(Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)) // No session - no validation.
        return;
    DoSomething();
}

The DoSomething() method call throws a NullReferenceException and it is simple enough that the only place it could do that was if HttpContext.Current.Session was null.

How can this be?

like image 760
Vilx- Avatar asked Jan 24 '26 17:01

Vilx-


1 Answers

At that time HttpContext.Current.Session may well be null. The event is firing at the point where the session is being aquired there is no guarantee that at this point it has been aquired. One reason you might hook this event is because you are providing a custom module to implement your own Session object. It would be here that such a custom module would set the Session.

If you want to use the Session object you should be using the PostAquireRequestState event.

like image 50
AnthonyWJones Avatar answered Jan 26 '26 19:01

AnthonyWJones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!