Session_Start 和 ASP.Net 异步 SessionState 模块

Session_Start and ASP.Net Async SessionState Module

我们最近集成了 ASP.Net Async SessionState Module 并开始在我们的 Global.asax Session_Start 事件处理程序中看到空引用异常。

我无法在本地复制它,它似乎并不总是在现场发生,但我相信这是我们试图在 Session_Start 中访问 HttpContext.Current 的时候。我的猜测是 HttpContext.Current 有时为空,因为会话初始化是异步的。

关于如何解决有什么建议吗?

也许答案太简单了,但我也时常看到这种情况,我建议您在 Session_Start 事件中保护您的代码,例如

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

如果您注意到这只是一个竞争条件,您的代码将做出正确的反应,而不仅仅是以 NullReferenceException 结束。

在这种特殊情况下,像这样保护它比在你引用它的任何地方添加 Elvis 运算符 (?.) 更好,因为这会导致你的 testing/troubleshooting 出现更复杂的场景。然而,在其他情况下,此运算符非常有用,例如 different context.

此外,在the link you provided,中我看到了提示"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."

也许您只需要实现 class 而不是使用 Session_Start - 因为这里总是作为参数给出的 HttpContext 而 Session_Start 只是为了向后兼容?