Checking session if empty or not

六眼飞鱼酱① 提交于 2019-11-29 00:39:39

问题


I want to check that session is null or empty i.e. some thing like this:

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

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

Or just

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

       // The code
    }

because sometimes when i check only with:

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

I face the following exception:

Null Reference exception


回答1:


Use this if the session variable emp_num will store a string:

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

If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.




回答2:


if (HttpContext.Current.Session["emp_num"] != null)
{
     // code if session is not null
}
  • if at all above fails.



回答3:


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".

There are a couple of ways, but the ones that springs to mind are:

if (Session["emp_num"] is string)
{
}

or

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

This will return null if the variable doesn't exist or isn't a string.




回答4:


You should first check if Session["emp_num"] exists in the session.

You can ask the session object if its indexer has the emp_num value or use string.IsNullOrEmpty(Session["emp_num"])




回答5:


If It is simple Seesion you can apply Null Check using if(Session["Session_name"] !=null)

but if it is a session of a list then You need to apply Either 1 or 2

Option 1:

    if (((List<int>)(Session["Session_name"])) != null && 
       (List<int>)Session["Session_name"])).Count > 0)

Option 2:

List<int> val= Session["Session_name"] as List<int>`;`//Get the value`
if (val.FirstOrDefault() != null)



回答6:


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

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

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

if(Session["emp_num"] != null)
{
    //cast it and use it
    //business logic
}


来源:https://stackoverflow.com/questions/7172910/checking-session-if-empty-or-not

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