May 21, 2015

A Better Way To Manage ASP.NET Session With Generic Wrapper

Before we get started, let us see the general way to use Session in ASP.NET

if (Session["UserName"] == null) 
{ 
    LabelUserName.Text = "Anonymous"; 
} 
else 
{ 
    LabelUserName.Text = (string)Session["UserName"]; 
} 

You can feel some drawbacks e.g. to check null reference, type safety, to cast object..etc.

Now add following class and see how it solves the issues:

 public class SessionManager
    {
       
        public static T Get<T>(string key)
        {
             object sessionObject = HttpContext.Current.Session[key];
             if (sessionObject == null)
             {
                 return default(T);
             }
             return (T)HttpContext.Current.Session[key];

        }

        public static T Get<T>(string key, T defaultValue)
        {
            object sessionObject = HttpContext.Current.Session[key];
            if (sessionObject == null)
            {
                HttpContext.Current.Session[key] = defaultValue;
            }

            return (T)HttpContext.Current.Session[key];
        }
 
        public static void Save<T>(string key, T entity)
        {
            HttpContext.Current.Session[key] = entity;
        }

        public static void Remove(string key)
        {
            HttpContext.Current.Session.Remove(key);
        }
    }

It contains a few generic methods to read and write objects from/to the Session. You can use the above class in your ViewModel or Business Object (BO) to generate strongly typed property from the Session like below:

  public String UserName
        {
            get { return SessionManager.Get<String>("UserName", "Anonymous"); }
            set { SessionManager.Save<String>("UserName", value);  }
        }

        public Int32 UserId
        {
            get { return SessionManager.Get<Int32>("UserId", -1); }
            set { SessionManager.Save<Int32>("UserId", value); }
        }

The Initial example can be written in following way:

LabelUserName.Text = SessionManager.Get<String>("UserName", "Anonymous");

OR

LabelUserName.Text = MyViewModel.UserName;

You can see how simple it is.

In this post, we created a generic version of getting and setting Session objects and created strongly typed properties using it.

Hope, It helps. Feel free to share your opinion in comment box.

One comment

  1. How will you remove the session variable from session using Remove method? I do not want to call Remove method by passing key. This way I will again be depending on strongly typed property to add/get session and then on hardcoded value/constant for removing session variable. Is there any alternative to this?

Leave a Reply

Your email address will not be published. Required fields are marked *