I have a class with a subroutine as follows:
Public Sub SetPermissions()
If IsNothing(HttpContext.Current.Session) Then
Exit Sub
Else
Dim session As HttpSessionState = HttpContext.Current.Session
If Not IsNothing(session("UserId")) Then '<-- exception occurs here
'Do Stuff
End If
End If
End Sub
I know that my session variable is not yet set, hence a null value, that’s why i’m trying to handle it with IsNothing, but my code still bugs out on me.
Any ideas?
Cheers
If you are going to try to access
Sessionvariables from Global.asax, you need to make sure you use an event that is fired afterSessionhas been initialized for the current request. If you take a look at the documentation on MSDN, you’ll see there are several events you can wire up in the Global.asax (check out the list of events in the section “The request is processed by the HttpApplication pipeline”).If you wire up those events, you should find that
Sessionis initialized beforeApplication_AcquireRequestStateis raised. If you move your code out ofApplication_AuthenticateRequestand intoApplication_AcquireRequestStatethen it should work properly.Note that I used the following code to test when
Sessionwould be initialized (C#, sorry). I wired up each event in order from the documentation, andApplication_AcquireRequestStatewas the first event where I sawsession == nullevaluate tofalse.