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

后端 未结 12 2546
野趣味
野趣味 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 16:12

    I also like to wrap session variables in properties. The setters here are trivial, but I like to write the get methods so they have only one exit point. To do that I usually check for null and set it to a default value before returning the value of the session variable. Something like this:

    string Name
    {
       get 
       {
           if(Session["Name"] == Null)
               Session["Name"] = "Default value";
           return (string)Session["Name"];
       }
       set { Session["Name"] = value; }
    }
    

    }

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

    In my opinion, the easiest way to do this that is clear and easy to read is:

     String sVar = (string)(Session["SessionVariable"] ?? "Default Value");
    

    It may not be the most efficient method, since it casts the default string value even in the case of the default (casting a string as string), but if you make it a standard coding practice, you find it works for all data types, and is easily readable.

    For example (a totally bogus example, but it shows the point):

     DateTime sDateVar = (datetime)(Session["DateValue"] ?? "2010-01-01");
     Int NextYear = sDateVar.Year + 1;
     String Message = "The Procrastinators Club will open it's doors Jan. 1st, " +
                      (string)(Session["OpeningDate"] ?? NextYear);
    

    I like the Generics option, but it seems like overkill unless you expect to need this all over the place. The extensions method could be modified to specifically extend the Session object so that it has a "safe" get option like Session.StringIfNull("SessionVar") and Session["SessionVar"] = "myval"; It breaks the simplicity of accessing the variable via Session["SessionVar"], but it is clean code, and still allows validating if null or if string if you need it.

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

    That is pretty much how you do it. However, there is a shorter syntax you can use.

    sSession = (string)Session["variable"] ?? "set this";
    

    This is saying if the session variables is null, set sSession to "set this"

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

    If you know it's a string, you can use the String.IsEmptyOrNull() function.

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

    Typically I create SessionProxy with strongly typed properties for items in the session. The code that accesses these properties checks for nullity and does the casting to the proper type. The nice thing about this is that all of my session related items are kept in one place. I don't have to worry about using different keys in different parts of the code (and wondering why it doesn't work). And with dependency injection and mocking I can fully test it with unit tests. If follows DRY principles and also lets me define reasonable defaults.

    public class SessionProxy
    {
        private HttpSessionState session; // use dependency injection for testability
        public SessionProxy( HttpSessionState session )
        {
           this.session = session;  //might need to throw an exception here if session is null
        }
    
        public DateTime LastUpdate
        {
           get { return this.session["LastUpdate"] != null
                             ? (DateTime)this.session["LastUpdate"] 
                             : DateTime.MinValue; }
           set { this.session["LastUpdate"] = value; }
        }
    
        public string UserLastName
        {
           get { return (string)this.session["UserLastName"]; }
           set { this.session["UserLastName"] = value; }
        }
    }
    
    0 讨论(0)
  • 2020-11-29 16:25

    Checking for nothing/Null is the way to do it.

    Dealing with object types is not the way to go. Declare a strict type and try to cast the object to the correct type. (And use cast hint or Convert)

     private const string SESSION_VAR = "myString";
     string sSession;
     if (Session[SESSION_VAR] != null)
     {
         sSession = (string)Session[SESSION_VAR];
     }
     else
     {
         sSession = "set this";
         Session[SESSION_VAR] = sSession;
     }
    

    Sorry for any syntax violations, I am a daily VB'er

    0 讨论(0)
提交回复
热议问题