16

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"];
        }
    }
}
Richard
  • 106,783
  • 21
  • 203
  • 265
Martijn
  • 24,441
  • 60
  • 174
  • 261
  • I see a potential problem here with the way you check the session value. You should have it as "var myvar = Session["value"];" Then check if that is null and cast it back. There is the possibility of the session becoming invalid between checking it and casting it. - Just thought you should know :) – TWith2Sugars Apr 17 '09 at 11:30
  • You do not need the `var myvar = Session["value"]; if(myvar != null)... ` as `if (Session["value"] != null)` will work just fine. I would also not worry about getting `Session["value"]` twice (once for != null and once to set variable) as the optimizer should take care of this. Note: you may find the [?? operator](http://msdn.microsoft.com/en-us/library/ms173224.aspx) useful: `mVar= (int)Session["value"] ?? 0;`. This will not fix the null Session problem which this thread is about (since it is not checking Session but the value from Session). – Trisped Apr 12 '12 at 00:00

8 Answers8

21

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
}
Nick Whaley
  • 2,729
  • 2
  • 21
  • 28
18

The session only really exists during the processing of an action - I wouldn't expect it to be valid in the constructor of a controller. For example, the controller might (for all I know) be re-used between requests.

You will need to do this either in the action (method), or (perhaps more appropriately) in an action filter, or the OnActionExecuting (etc) method(s):

public abstract class ControllerBase : Controller
{
    protected override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        // code involving this.Session // edited to simplify
        base.OnActionExecuting(filterContext); // re-added in edit
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Thnx. But why do i need to use filterContext.RequestContext.HttpContext.Session["val"] instead of Session["val"] ? And do i still need to invoke base.OnActionExecuting(filterContext);? – Martijn Apr 17 '09 at 10:18
  • 1
    Okay :) Can you tell me briefly what filterContext is about? – Martijn Apr 17 '09 at 11:00
  • That is just the way that it passes additional state (not normally directly available in members) to the filter methods. IIRC, it is mentioned a bit more in ASP.NET MVC In Action (Manning). – Marc Gravell Apr 17 '09 at 11:36
  • Erm... ASP.NET MVC In Action, as already mentioned. There are others, though. – Marc Gravell Apr 17 '09 at 12:06
  • @MarcGravell http://stackoverflow.com/questions/17362072/checking-session-exists-or-not-mvc3 – Sharun Jun 28 '13 at 15:41
2

You'll have to do it like this-

if(null != HttpContext.Current.Session["Value"])
{
    //Code here.
}
Kirtan
  • 21,295
  • 6
  • 46
  • 61
  • 'System.Web.HttpContextBase' does not contain a definition for 'Current' and no extension method 'Current' accepting a first argument of type 'System.Web.HttpContextBase' could be found (are you missing a using directive or an assembly reference?) – Martijn Apr 17 '09 at 10:02
  • When i leave the Current object, it does work. But I still get the error. I think it has something to do with what Partario says: The Session object itself is null. Now lat's foound out why :S... – Martijn Apr 17 '09 at 10:03
  • Do it like this it will work: System.Web.HttpContext.Current.Session["Value"] – t_plusplus Nov 05 '15 at 12:23
2

You're getting this error because the "Session" object is null. Therefore it's impossible to look at the ["value"] bit of it. I'm not familiar with MVC, but either there's a bigger problem whereby the Session object isn't being created, or you're accessing it at the wrong point of the lifecycle, or you just need a test to check if Session != null.

Graham Clark
  • 12,886
  • 8
  • 50
  • 82
1
if(Session != null && Session["name"] != null && Session["name"].ToString()!="")
{
   //fire code
}
Behnam
  • 6,244
  • 1
  • 39
  • 36
1

I solve by this way:

if (Session.Count > 0 && Session["mySessionVariable"].ToString() != null)
{

}
1

The syntax used by you:

if (Session["mySessionVariable"] != null)
{

}

... is the correct way to check for a Session object in ASP.NET. I suspect that the problem is because you are using ASP.NET MVC.

Maybe some of our MVC experts can enlighten us as to the correct way of doing this in ASP.NET MVC.

Edit: I see that Marc Gravell has posted his answer while I'm typing this. That should be illuminatory.

Cerebrus
  • 25,615
  • 8
  • 56
  • 70
0

You also can use:

if (Session == null || String.IsNullOrEmpty((string)Session["session_object"])){
   // Do something
}