Checking if session variable is null returns nullreferenceexception

I have a list of objects stored in a session variable. But when I check that the session variable is not null, it gives me NullReferenceException: Object reference not set to an instance of an object.

if(Session["object"] == null)  //error occurs here
{
     Session["object"] = GetObject();
     return Session["object"] as List<object>;
}
else
{
    return Session["object"] as List<object>;
}

How to check if a session is null?

edit: I also tried

if(Session["object"] != null)
+4
source share
4 answers

edit: I also tried

if(Session["object"] != null)

, , , Session . null, Session["object"] , "", , , , , null . , Session , , Session["object"] null:

if (Session != null)
{
    if(Session["object"] == null)
    {
         Session["object"] = GetObject();
         return Session["object"] as List<object>;
    }
    else
    {
        return Session["object"] as List<object>;
    }
}
else
{
    return null;
}
+6

, Session != null? this.Session this.Session["Key"] null, . , Session , , .

0

You check your GetObject () method ... it can return null ...

0
source

Try checking if (!Session.ContainsKey("object"))after checking if (Session != null). If these checks pass, then it Session["object"]should be in order.

0
source

Source: https://habr.com/ru/post/1524289/


All Articles