I always use the wrapper class around an ASP.NET session to simplify access to session variables:
public class MySession { // private constructor private MySession() { FillOrder = new List<string>(); } // Gets the current session. public static MySession Current { get { var session = (MySession)HttpContext.Current.Session["__MySession__"]; if (session == null) { session = new MySession(); HttpContext.Current.Session["__MySession__"] = session; } return session; } } // **** add your session properties here, eg like this: public List<string> FillOrder {get; set; } public string Property1 { get; set; } public DateTime MyDate { get; set; } public int LoginId { get; set; } }
This class stores one instance by itself in an ASP.NET session and allows you to access your session properties with a safe type from any class, for example, for example:
MySession.Current.FillOrder.Add(accordion.ID); int loginId = MySession.Current.LoginId; string property1 = MySession.Current.Property1; MySession.Current.Property1 = newValue; DateTime myDate = MySession.Current.MyDate; MySession.Current.MyDate = DateTime.Now;
This approach has several advantages:
- you can initialize your session variables in the constructor (i.e.
new List<string> ) - it will save you a lot of casting types
- you do not need to use hard-coded session keys throughout the application (for example, Session ["loginId"]
- You can document your session elements by adding XML document comments to MySession properties.
source share