StevieB
StevieB

Reputation: 6533

ASP.NET Session Object reference not set to instance of an object

Hey Just wondering how the following can happen

Object reference not set to an instance of an object.

customerName.Text = Session("userName").ToString()

    If (Session("userId") Is Nothing) Then
        Response.Redirect(ConfigurationManager.AppSettings("site_base_url").ToString & "login/", False)
    End If

    customerName.Text = Session("userName").ToString()

Now I currently have no session set on this page. So the session is NULL but i am just wondering why my if statement is taking care of this problem, why does it even try to get to the next part i.e. Response.Write ?

Upvotes: 1

Views: 11452

Answers (3)

Vinay
Vinay

Reputation: 1064

Your

customerName.Text = Session("userName").ToString();

will be executed no matter what the value of the session is. In the if condition, you are checking for the (Session("userId") and not Session("userName"). Both of them are different session variables. If for some reason Session("userName") value is not assigned prior, you will get the "Object reference not set to an instance of an object" exception. I would do a session null check first before assigning the value to customerName.Text

if(Session("userName") IsNot Nothing) Then
    customerName.Text = Session("userName").ToString();     

Upvotes: 0

Paul Sasik
Paul Sasik

Reputation: 81429

From your code snippet it looks like the line Response.Write(Session("UID").ToString) will always be executed regardless of what happens with the if statement above it.

I wonder if the weird indentation isn't confusing you. Try looking at it like this:

If (Session("userName") IsNot Nothing) Then
    customerName.Text = Session("userName").ToString()
End If

Response.Write(Session("UID").ToString)

Notice that I aligned the End If with the corresponding If above and the Response.Write... as well. The Response.Write... line clearly sits outside of the If block and since there is not return or break or continue in the If block it will always get executed.

And btw, it's probably not the Session object that is null. You are calling ToString on an item you assume to be contained in the Session object. It's more likely that the Session does not contain a "UID" entry.

Upvotes: 1

Curtis
Curtis

Reputation: 103358

Response.Write() is outside of the IF statement, so whether or not the Session Is Nothing, the Response.Write() method will be ran.


Alternatively, perhaps youre trying to assign a value to the Session if it doesnt already have one? In this case, I think you have your code in reverse:

customerName.Text = Session("userName").ToString()

Should be:

Session("userName") = customerName.Text

Upvotes: 0

Related Questions