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

北慕城南 提交于 2019-12-10 13:39:53

问题


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


回答1:


if(Session["TenantSessionId"] != null)
{
  // cast it and use it
  // The code
}



回答2:


As [] is act as 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
}



回答3:


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.




回答4:


Check if the session is empty/Null or not

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

//here write code for logic

}




回答5:


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
}


来源:https://stackoverflow.com/questions/41855490/how-to-check-if-session-value-is-null-or-session-key-does-not-exist-in-asp-net-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!