Reputation: 1806
I want to count my users and this is the code below that is in my dll file:
public static class UserCount
{
public static void add()
{
HttpContext.Current.Application.Lock();
int count = (int) HttpContext.Current.Application["CountOfUsers"];
count++;
HttpContext.Current.Application["CountOfUsers"]=count;
HttpContext.Current.Application.UnLock();
}
public static void subtract()
{
HttpContext.Current.Application.Lock();//error : HttpContext.Current is null. why?
int count = (int) HttpContext.Current.Application["CountOfUsers"];
count--;
HttpContext.Current.Application["CountOfUsers"]=count;
HttpContext.Current.Application.UnLock();
}
}
I have set Session.TimeOut=1;
and after one minute the the method below in Global.asax file, this will run:
protected void Session_End(object sender, EventArgs e)
{
UserCount.subtract();
}
Why is HttpContext.Current
null in the subtract
method causing it to throw an exception?
Upvotes: 1
Views: 9744
Reputation: 42494
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.
Upvotes: 4