Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I get an error when I do the following:

if(Session["value"] != null)
{
   // code
}

The error i get is this:

Object reference not set to an instance of an object.

Why is this? I always check my session this way? I am using the MVC Framework, does this has something to do with it?

EDIT:

The code is in the constructor of a Controller:

public class MyController : ControllerBase
{
    private int mVar;

    public MyController()
    {
        if (Session["value"] != null)
        {
            mVar= (int)Session["value"];
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
638 views
Welcome To Ask or Share your Answers For Others

1 Answer

The [] is an indexer, it acts like a method on the class.

In this case, Session is null and you cannot perform the indexing on it.

Do this:

if(Session != null && Session["value"] != null)
{
   // code
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...