Wrapping Session States

A common way of using session states in ASP.NET is to simply use the Session object in your code behind file, for example you might say:

Session["MyFirstName"] = "Brian";
Session["MyAge"] = "24";        // Not my real age :-)

Another option would be to wrap these Session states into a class. You’d do this by creating the class, I usually name this class “MySession”, with code that looks like this:

public static string firstName    {
get { return HttpContext.Current.Session["MyFirstName"].ToString(); }
set { HttpContext.Current.Session["MyFirstName"] = value; }
}
public static int age    {
get { return Convert.ToInt32(HttpContext.Current.Session["MyAge"].ToString()); }
set { HttpContext.Current.Session["MyAge"] = value; }
}

This give you a few advantages:

  1. You now have all your session states located in a single file in source code.
  2. You access the session states using the MySession.firstName and MySession.age
  3. Because you are using a class, IntelliSense now works! You don’t have to remember that the session state name was “MyFirstName”. All you need to remember is MySession. Visual Studio will give you the rest.
  4. Strongly typed session states. Notice that the type of MySession.age is an integer. It will throw an exception if you try to assign it a value of a different type.

Wrapping your session states into a class may add a little to the number of lines that you write. In the long run, however, it will likely save you time because you will always know what session states are available to you in your application. No more trying to remember what you named it 6 months ago when you are asked to make a change to the application.

I’ve used this technique in a number of projects, and it has worked well. Thanks to Paul Sheriff for sharing this tip when presenting at the Iowa Dot Net Users Group.

Advertisements

2 comments so far

  1. […] Brian Webster’s Blog Web Development and Other Ramblings « Wrapping Session States […]

  2. larscorneliussen on

    Hi,

    there are just too many possible NullReferenceExceptions in “HttpContext.Current.Session[“MyFirstName”].ToString()” 🙂

    Maybe you like my implementation: http://startbigthinksmall.wordpress.com/2008/05/14/how-to-wrap-the-aspnet-session-state/


Comments are closed.

%d bloggers like this: