.netasp.netvb.netsession

Check if session item exists fails itself with object reference not set error


I'm having problem regarding session items. Before I use them, I want to check if they exists, but using this codes gives me error:

If (Session("SomeSessionItem") Is Nothing) Then
...
End If

This is the error:

Object reference not set to an instance of an object.

I think Session("SomeSessionItem") tries to acquire the value of the session item. If the item doesn't exists then it throws exception. But how do I check if a session item exists before using them?


Solution

  • Does that work for you?

    If (Session IsNot Nothing)
        Dim item as Object = Session("SomeSessionItem")
        If (item IsNot Nothing)
        ...
        End If
    End If
    

    Also, you may need to check HttpContext.Current.Session rather than simply Session if you're seeing the the following error:

    Session does not exist in this context