Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if session value is null or session key does not exist in asp.net mvc - 5

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

like image 486
Unbreakable Avatar asked Jan 25 '17 15:01

Unbreakable


People also ask

How do you check session key is exist or not?

Answers. Morover put a breakpoint in the session and check the exact value of session after clearing.

How do I check if a session variable has a value?

You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable.

How check session is set or not in C#?

You need to check that Session["emp_num"] is not null before trying to convert it to a string otherwise you will get a null reference exception. I'd go with your first example - but you could make it slightly more "elegant". This will return null if the variable doesn't exist or isn't a string.

Why session is null in MVC?

Why is Session null in the constructors of Controllers? It can be accessed from Action methods. Presumably, because the MVC Routing framework is responsible for newing-up a Controller, it just hasn't (re-)instantiated the Session at that point.


1 Answers

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.

like image 127
Chris Pratt Avatar answered Sep 21 '22 02:09

Chris Pratt