What is the best way to determine a session variable is null or empty in C#?

后端 未结 12 2545
野趣味
野趣味 2020-11-29 15:33

What is the best way to check for the existence of a session variable in ASP.NET C#?

I like to use String.IsNullOrEmpty() works for strings and wonder

相关标签:
12条回答
  • 2020-11-29 15:59

    To follow on from what others have said. I tend to have two layers:

    The core layer. This is within a DLL that is added to nearly all web app projects. In this I have a SessionVars class which does the grunt work for Session state getters/setters. It contains code like the following:

    public class SessionVar
    {
        static HttpSessionState Session
        {
            get
            {
                if (HttpContext.Current == null)
                    throw new ApplicationException("No Http Context, No Session to Get!");
    
                return HttpContext.Current.Session;
            }
        }
    
        public static T Get<T>(string key)
        {
            if (Session[key] == null)
                return default(T);
            else
                return (T)Session[key];
        }
    
        public static void Set<T>(string key, T value)
        {
            Session[key] = value;
        }
    }
    

    Note the generics for getting any type.

    I then also add Getters/Setters for specific types, especially string since I often prefer to work with string.Empty rather than null for variables presented to Users.

    e.g:

    public static string GetString(string key)
    {
        string s = Get<string>(key);
        return s == null ? string.Empty : s;
    }
    
    public static void SetString(string key, string value)
    {
        Set<string>(key, value);
    }
    

    And so on...

    I then create wrappers to abstract that away and bring it up to the application model. For example, if we have customer details:

    public class CustomerInfo
    {
        public string Name
        {
            get
            {
                return SessionVar.GetString("CustomerInfo_Name");
            }
            set
            {
                SessionVar.SetString("CustomerInfo_Name", value);
            }
        }
    }
    

    You get the idea right? :)

    NOTE: Just had a thought when adding a comment to the accepted answer. Always ensure objects are serializable when storing them in Session when using a state server. It can be all too easy to try and save an object using the generics when on web farm and it go boom. I deploy on a web farm at work so added checks to my code in the core layer to see if the object is serializable, another benefit of encapsulating the Session Getters and Setters :)

    0 讨论(0)
  • 2020-11-29 15:59

    This method also does not assume that the object in the Session variable is a string

    if((Session["MySessionVariable"] ?? "").ToString() != "")
        //More code for the Code God
    

    So basically replaces the null variable with an empty string before converting it to a string since ToString is part of the Object class

    0 讨论(0)
  • 2020-11-29 16:01

    The 'as' notation in c# 3.0 is very clean. Since all session variables are nullable objects, this lets you grab the value and put it into your own typed variable without worry of throwing an exception. Most objects can be handled this way.

    string mySessionVar = Session["mySessionVar"] as string;
    

    My concept is that you should pull your Session variables into local variables and then handle them appropriately. Always assume your Session variables could be null and never cast them into a non-nullable type.

    If you need a non-nullable typed variable you can then use TryParse to get that.

    int mySessionInt;
    if (!int.TryParse(mySessionVar, out mySessionInt)){
       // handle the case where your session variable did not parse into the expected type 
       // e.g. mySessionInt = 0;
    }
    
    0 讨论(0)
  • 2020-11-29 16:03

    in this way it can be checked whether such a key is available

    if (Session.Dictionary.ContainsKey("Sessionkey"))  --> return Bool
    
    0 讨论(0)
  • 2020-11-29 16:05

    Are you using .NET 3.5? Create an IsNull extension method:

    public static bool IsNull(this object input)
    {
        input == null ? return true : return false;
    }
    
    public void Main()
    {
       object x = new object();
       if(x.IsNull)
       {
          //do your thing
       }
    }
    
    0 讨论(0)
  • 2020-11-29 16:08

    It may make things more elegant to wrap it in a property.

    string MySessionVar
    {
       get{
          return Session["MySessionVar"] ?? String.Empty;
       }
       set{
          Session["MySessionVar"] = value;
       }
    }
    

    then you can treat it as a string.

    if( String.IsNullOrEmpty( MySessionVar ) )
    {
       // do something
    }
    
    0 讨论(0)
提交回复
热议问题