Accessing session variables within classes in App_Code

Because ASP.NET pages contain a default reference to the System.Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an .aspx page without the fully qualified class reference to HttpContext. If you try to access this property within a class in App_Code, the property will not be available to you unless your class derives from the Page Class.

In this case, you can always use a wrapper class around the ASP.NET session to simplify access to session variables.

Sample Code:

public class YourSession
private YourSession()
Property1 = “default value for property 1”;
Property2 = “default value for property 2”;
Property3 = “default value for property 3”;

public static YourSession Current
YourSession session =
if (session == null)
session = new YourSession();
HttpContext.Current.Session[“__YourSession__”] = session;
return session;

public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }

This above class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class. The session properties can be assessed in the following manner:

string property1 = YourSession.Current.Property1;
YourSession.Current.Property1 = new value for property 1″;

string property2 = YourSession.Current.Property2;
YourSession.Current.Property2 = new value for property 2″;

string property3 = YourSession.Current.Property3;
YourSession.Current.Property3 = new value for property 3″;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: