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

后端 未结 12 2645
野趣味
野趣味 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: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; }
        }
    }
    

提交回复
热议问题