17 June 2013
Storing and retrieving information from the session state is a common use case in most web applications. For example, user information might be retrieved from the database and then stored in the session upon log in of a user. Following this approach, database calls that retrieve information about a user are reduced (ideally to one call only).
In small or simple applications, retrieving from and assigning values to the session are done by directly accessing the Session object with typing the key:
// Set session variable
Session["MyVar"] = "Hello, world!";
// Retrieve session variable
string myVar = null;
object sessionVar = Session["MyVar"];
if (sessionVar != null)
{
myVar = sessionVar.ToString();
}
While accessing the session value this way works, it has the following disadvantages:
We can get rid of these disadvantages by making Session access the exclusive responsibility of a class. Below is an example of such a class.
public sealed class SessionHelper
{
private SessionHelper() { }
// Fully qualified namespace used here for clarity purposes
private static System.Web.SessionState.HttpSessionState Session { get { return System.Web.HttpContext.Current.Session; } }
// Session property: username (string)
public static string Username
{
get
{
if (Session["Username"] == null)
{
return String.Empty;
}
return Session["Username"].ToString();
}
set
{
Session["Username"] = value;
}
}
}
Now the session variable is wrapped inside a property, which has an enforceable type. In addition, implementation details (such as the name of the session key or how to handle null values) are now handled by this class and not on the client, resulting in a better separation of concerns.
In this post you have seen how to wrap session access in a class. I would recommend handling session variables in this manner (as opposed to direct access) in all applications regardless of size.