views:

252

answers:

2

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?

A: 

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.

AnthonyWJones
A: 

In this method the Session object is not yet constructed so it is inaccessible. Try to do the work in any method that is executed after this method. Maybe Application_PreRequestHandlerExecute or look at this page to see the order of execution of methods in global.asax file http://articles.techrepublic.com.com/5100-10878%5F11-5771721.html

The remaining events deal with application requests, and they're triggered in the following order:

* Application_BeginRequest
* Application_AuthenticateRequest
* Application_AuthorizeRequest
* Application_ResolveRequestCache
* Application_AcquireRequestState
* Application_PreRequestHandlerExecute
* Application_PreSendRequestHeaders
* Application_PreSendRequestContent
* <<code is executed>>
* Application_PostRequestHandlerExecute
* Application_ReleaseRequestState
* Application_UpdateRequestCache
* Application_EndRequest
B-Rain
Funny, because it has always worked both on my and many other machines.
Vilx-
Are you using AJAX call? If it is the case it might be a source of problem
B-Rain
How is an AJAX call any different for a server? O_o
Vilx-