Thursday, February 6, 2014

C# Session Wrapper

The following C# class is a simple implementation of a wrapper class for sessions. It allows getting, setting and removing of objects (of  a defined type) from the session.
public class SessionWrapper
{
    private 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;
    }
 
    public static void Remove<T>(string key)
    {
        if (Session[key] != null)
        {
            Session.Remove(key);
        }
    }
}

No comments:

Post a Comment