14

I have one ASP.Net MVC - 5 application and I want to check if the session value is null before accessing it. But I am not able to do so.

//Set
System.Web.HttpContext.Current.Session["TenantSessionId"] = user.SessionID;
// Access
int TenantSessionId = (int)System.Web.HttpContext.Current.Session["TenantSessionId"];

I tried many solutions from SO

Attempt

if (!string.IsNullOrEmpty(Session["TenantSessionId"] as string))
 {
                //The code
 }

Kindly guide me.

Error: NULL Reference

Unbreakable
  • 7,776
  • 24
  • 90
  • 171

6 Answers6

27
if(Session["TenantSessionId"] != null)
{
  // cast it and use it
  // The code
}
Ahmed
  • 1,542
  • 2
  • 13
  • 21
7

The NullReferenceException comes from trying to cast a null value. In general, you're usually better off using as instead of a direct cast:

var tenantSessionId = Session["TenantSessionId"] as int?;

That will never raise an exception. The value of tenantSessionId will simply be null if the session variable is not set. If you have a default value, you can use the null coalesce operator to ensure there's always some value:

var tenantSessionId = Session["TenantSessionId"] as int? ?? defaultValue;

Then, it will either be the value from the session or the default value, i.e. never null.

You can also just check if the session variable is null directly:

if (Session["TenantSessionId"] != null)
{
    // do something with session variable
}

However, you would need to confine all your work with the session variable to be inside this conditional.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • I was using `as` but I was getting some error one of the famous guy in SO "Steve Muecke" told me that better to do classical typecasting. because integer is not reference type and all of that. P.S: I did not use "int ?" I had just `int` in the end – Unbreakable Jan 25 '17 at 15:54
  • LINK http://stackoverflow.com/questions/41839234/how-to-access-session-variable-in-asp-net-mvc/41839632#41839632 – Unbreakable Jan 25 '17 at 15:57
  • Yeah, you can't use `as` with a non-nullable, since it returns `null` rather than raising an exception if the value can't be cast. However, if you null coalesce, you can still store in a non-nullable. – Chris Pratt Jan 25 '17 at 16:01
6

[] acts as an indexer (like a method on the class) and in this case, session is null and you cannot perform indexing on it.

Try this..

if(Session != null && Session["TenantSessionId"] != null)
{
   // code
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Rahul Hendawe
  • 902
  • 1
  • 14
  • 39
  • checking this `Session["TenantSessionId"] != null` works for me. Do I need to check for bare `session too`? – Unbreakable Jan 25 '17 at 15:49
  • 1
    yes, as I mentioned `[]` this will act as `indexer` and so, sometime it happens when value in a `session` variable is null then it will might throw an error of `null reference`. – Rahul Hendawe Jan 25 '17 at 15:53
  • I got "The name 'Session' does not exist in the current context", do I need to add any namespaces here? I did a ctrl + dot(.), but there is no fix for it. – paraJdox1 Dec 13 '21 at 06:35
1

Check if the session is empty/Null or not in C# MVC Version Lower than 5.

if (!string.IsNullOrEmpty(Session["TenantSessionId"] as string))
{
    //cast it and use it
    //business logic
}

Check if the session is empty/Null or not in C# MVC Version Above 5.

if(Session["TenantSessionId"] != null)
{
    //cast it and use it
    //business logic
}
Pergin Sheni
  • 393
  • 2
  • 11
vishpatel73
  • 317
  • 4
  • 10
0

There is a case when you want to check only for existence of the key itself but not the content. Above method fails when you Session key value is null also.

Eg:

Session["myKey"] = null;
if(Session["myKey"]!=null){}

In above code, I want to check if only the key (not value) exists, I will get false. But the key does exists.

So the only way I could separate this existence check, is by basically checking each key.

static bool check_for_session_key(string SessionKey)
{
     foreach (var key in HttpContext.Current.Session.Keys)
     {
         if (key.ToString() == SessionKey) return true;
     }
     return false;
}
if(check_for_session_key("myKey")){} //checks for the key only

Let me know if you know better way.

InGeek
  • 2,532
  • 2
  • 26
  • 36
-1

Check if the session is empty/Null or not

if (!string.IsNullOrEmpty(Session["TenantSessionId"] as string)) {

//here write code for logic

}

Pergin Sheni
  • 393
  • 2
  • 11