Typed session data in ASP.NET made easier still
Philippe Leybaert is unimpressed with Microsoft’s Web Client Software Factory approach for typed session data and offers his own Typed session data made (very) easy which still seems overkill to me comprising as it does of generics, a delegate a helper class to achieve the desired effect. (Whilst you are there check out his very interesting MVC project for ASP.NET called ProMesh)
The solution which I have been using since my .NET 1.1 days is much simpler still and involves nothing more than creating a plain class with properties for every session variable and a static get accessor that obtains or creates it on the HttpContext similar to a singleton.
Here’s an example with the important Current property (slightly cleaned up and improved for this post ;-)
public class MySession {
public string Name;
public int LoginID;
public int CustomerID;
public static MySession Current {
get {
MySession currentSession = HttpContext.Current.Session["_session"] as MySession;
if (currentSession == null) {
currentSession = new MySession();
HttpContext.Current.Session["_session"] = currentSession;
}
return currentSession;
}
}
}
Using the session data then simply involves operations like:
MySession.Current.Name = NameTextBox.Text;
NameLabel.Text = MySession.Current.Name;
This solution is a lot clearer however all of these solutions use HttpContext.Session which is actually supposed to be there for compatibility with ASP.
Ideally Microsoft would provide us with an option in web.config whereby we can choose our session class and it would just instantiate and track it as part of the session life-cycle.
[)amien
5 responses