Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Easy Sessions using Extension Methods

0.00/5 (No votes)
22 May 2014 1  
How to make sessions easy to use by extending .NET object class

Introduction

Working with sessions in ASP.NET can often be uncomfortable and lead to errors. By using these extension methods, this task will be much easier.

Background

You are used to program with C#, ASP.NET, sessions and extension methods.

Using the Code

The Extension Methods

Extending object class in order to add all objects methods to save sessions.

public static class Sessions
{
    public static object ToSession(this object obj)
    {
        string sessionId = obj.GetType().FullName;

        System.Web.HttpContext.Current.Session.Remove(sessionId);
        System.Web.HttpContext.Current.Session.Add(sessionId, obj);

        return obj;
    }

    public static object FromSessionOrNew(this object obj, object objNew=null)
    {
        string sessionId = obj.GetType().FullName;

        if ((System.Web.HttpContext.Current.Session[sessionId] as object) != null){
            obj = System.Web.HttpContext.Current.Session[sessionId] as object;
        }
        else{
            obj = objNew;

            System.Web.HttpContext.Current.Session.Remove(sessionId);
            System.Web.HttpContext.Current.Session.Add(sessionId, obj);
        }

        return obj;
    }

    public static void RemoveFromSession(this object obj)
    {
        string sessionId = obj.GetType().FullName;
        System.Web.HttpContext.Current.Session.Remove(sessionId);
    }
}

Sample of Use of FromSessionOrNew

It is an instance of an object from session. Optionally, if session is null, a default instance (Foo() {Name="Lois"}) can be returned and stored in session, so, this method is useful both get an object from session and store it for the first time.

public class Foo
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public ActionResult Index()
{
    foo = (Foo)new Foo().FromSessionOrNew(new Foo() { Name = "Lois", Age = 30 });
}  

To store an object to session or remove it, use these methods:

foo.ToSession();
foo.RemoveSession(); 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here