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();