简体   繁体   中英

Session_Start and ASP.Net Async SessionState Module

We recently integrated the ASP.Net Async SessionState Module and have started seeing null ref exceptions in our Global.asax Session_Start event handler.

I can't replicate it locally, and it doesn't appear to happen all the time in live, but I believe this is when we attempt to access HttpContext.Current in Session_Start. My guess is HttpContext.Current is sometimes null, because Session initialization is asynchronous.

Any suggestions as to how to address?

Maybe the answer is too simple, but I have also seen this from time to time, and I'd suggest that you safeguard your code inside the Session_Start event like

if (HttpContext.Current !== null)
{
    // do your actions with the Current object
}
else
{
    // possibly add some logging here to see what's going on
}

If you notice it is just a race condition, your code will react properly and not just end up in a NullReferenceException.

Safeguarding it like this is in this particular case better than adding Elvis operators ( ?. ) everywhere you're referencing it because that will lead into more complex scenarios for your testing/troubleshooting. In other cases, however, this operator is quite useful, for example in this different context.

Additionally, In the link you provided, I saw the hint "To implement your own async sessionstate provider which works with Microsoft.AspNet.SessionState.SessionStateModule, all you need to do is to implement a concrete SessionStateStoreProviderAsyncBase class which is included in the Microsoft.AspNet.SessionState.SessionStateModule NuGet package."

Maybe you just need to implement that class rather than using Session_Start - because here is always a HttpContext given as parameter and Session_Start is just there for backwards-compatibility?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM