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("SomeSes开发者_如何学CsionItem")
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?
- I have a page
Home.aspx
. - In the
Home.aspx.vb
, I instantiate a WebUserControlSomeControl.ascx
. Note that inHome.aspx.vb
event handlerPage_Load
I can use a condition to check session without getting an exception. - Inside
SomeControl.ascx.vb
I'm trying to access the session, here's where the exception occurs.
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
If you try to use sessions before the session object itself is created, you receive this behavior. Note that the Session object is not available at all times in the process of a request. You can check for Session itself to be Nothing.
It is guaranteed created after the Session_Start
event fired which you can check in global.asax.
In case your code runs inside the code-behind of your page, there are scenario's where the session state is not yet available. However, inside Page_Load it is available, check there.
Finally: when .EnableSessionstate="false"
is set for your page or application-wide, you cannot access the session object.
Edit:
Maybe you mean instead of If (Session("SomeSessionItem") Is Nothing) Then
the following?
If (Session("SomeSessionItem") IsNot Nothing) Then
'... do someting, i.e.:'
Dim sessionItem As String = CType(Session("SomeSessionItem"), String)
You need to use Item
on Session
If Session.Item("SomeSessionItem") Is Nothing Then
' No such value in session state, take appropriate action.
End If
Are you sure the error is coming from your If
line? What are you doing inside the If
?
I ask because you say
Before I use them, I want to check if they exists
and then check that they don't exist.
My guess would be that the code inside your If
block is reading the value from Session
and attempting to use it, right after you've checked that it doesn't exist :)
Use this
VB.NET
IF HttpContext.Current IS NOTHING Then
------Your Code
Else
----Your Code
End IF
C#
IF Session("XYZ") == NULL
{
---- Your Code
}
Else
{
---- Your Code
}
精彩评论