Why is HttpContext.Current null during the Session_End event?

Why is HttpContext.Current null during the Session_End event?

On Session_End there is no communication necessarily involved with the browser so there is no HttpContext to refer to which explains why it is null.

Looking at your code you seem to be intersted in the Application cache. That is available via Application property on the HttpApplication instance.

If you create an overload on your UserCount class that takes an HttpApplicationState you'll be fine:

public static void subtract(HttpApplicationState appstate)
{
    appstate.Lock();
    int count = (int) appstate["CountOfUsers"];
    count--;
    appstate["CountOfUsers"]=count;
    appstate.UnLock();
}

You can use this from Session_End like so:

protected void Session_End(object sender, EventArgs e)
{
    UserCount.subtract(Application);
}

This works because global_asax is technically an subclass from HttpApplication and so all its members are accessible from the global_asax file.

The other implementation of substract can be used when there is an HttpContext.

原文地址:https://www.cnblogs.com/chucklu/p/15357117.html