Checking session if empty or not

后端 未结 6 830
萌比男神i
萌比男神i 2020-12-28 13: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\"         


        
相关标签:
6条回答
  • 2020-12-28 14:04

    If It is simple Session you can apply NULL Check directly Session["emp_num"] != null

    But if it's a session of a list Item then You need to apply any one of the following option

    Option 1:

    if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
     {
     //Your Logic here
     }
    

    Option 2:

    List<int> val= Session["emp_num"] as List<int>;  //Get the value from Session.
    
    if (val.FirstOrDefault() != null)
     {
     //Your Logic here
     }
    
    0 讨论(0)
  • 2020-12-28 14:11

    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"])

    0 讨论(0)
  • 2020-12-28 14:18

    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.

    0 讨论(0)
  • 2020-12-28 14:18

    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.

    0 讨论(0)
  • 2020-12-28 14:26
    if (HttpContext.Current.Session["emp_num"] != null)
    {
         // code if session is not null
    }
    
    • if at all above fails.
    0 讨论(0)
  • 2020-12-28 14:26

    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
    }
    
    0 讨论(0)
提交回复
热议问题