How to access session variables from any class in ASP.NET?

I have created a class file in the App_Code folder in my application. I have a session variable


I want to access this session variables in my class, but when I am writing the following line then it gives error


Can anyone tell me how to access session variables within a class which is created in app_code folder in ASP.NET 2.0 (C#)


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

(Updated for completeness)
You can access session variables from any page or control using Session["loginId"] and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].

But please read on for my original answer…

I always use a wrapper class around the ASP.NET session to simplify access to session variables:

public class MySession
    // private constructor
    private MySession()
      Property1 = "default value";

    // Gets the current session.
    public static MySession Current
        MySession session =
        if (session == null)
          session = new MySession();
          HttpContext.Current.Session["__MySession__"] = session;
        return session;

    // **** add your session properties here, e.g like this:
    public string Property1 { get; set; }
    public DateTime MyDate { get; set; }
    public int LoginId { get; set; }

This 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, e.g like this:

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:

  • it saves you from a lot of type-casting
  • you don’t have to use hard-coded session keys throughout your application (e.g. Session[“loginId”]
  • you can document your session items by adding XML doc comments on the properties of MySession
  • you can initialize your session variables with default values (e.g. assuring they are not null)

Method 2

Access the Session via the thread’s HttpContext:-


Method 3

The problem with the solution suggested is that it can break some performance features built into the SessionState if you are using an out-of-process session storage. (either “State Server Mode” or “SQL Server Mode”). In oop modes the session data needs to be serialized at the end of the page request and deserialized at the beginning of the page request, which can be costly. To improve the performance the SessionState attempts to only deserialize what is needed by only deserialize variable when it is accessed the first time, and it only re-serializes and replaces variable which were changed. If you have alot of session variable and shove them all into one class essentially everything in your session will be deserialized on every page request that uses session and everything will need to be serialized again even if only 1 property changed becuase the class changed. Just something to consider if your using alot of session and an oop mode.

Method 4

The answers presented before mine provide apt solutions to the problem, however, I feel that it is important to understand why this error results:

The Session property of the Page returns an instance of type HttpSessionState relative to that particular request. Page.Session is actually equivalent to calling Page.Context.Session.

MSDN explains how this is possible:

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.

However, When 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.

My solution to this oft-encountered scenario is that I never pass page objects to classes. I would rather extract the required objects from the page Session and pass them to the Class in the form of a name-value collection / Array / List, depending on the case.

Method 5

In core this works differerently:

public class SomeOtherClass
    private readonly IHttpContextAccessor _httpContextAccessor;
    private ISession _session => _httpContextAccessor.HttpContext.Session;

    public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
        _httpContextAccessor = httpContextAccessor;

    public void TestSet()
        _session.SetString("Test", "Ben Rules!");

    public void TestGet()
        var message = _session.GetString("Test");


Method 6

I had the same error, because I was trying to manipulate session variables inside a custom Session class.

I had to pass the current context (system.web.httpcontext.current) into the class, and then everything worked out fine.


Method 7

This should be more efficient both for the application and also for the developer.

Add the following class to your web project:

/// <summary>
/// This holds all of the session variables for the site.
/// </summary>
public class SessionCentralized
protected internal static void Save<T>(string sessionName, T value)
    HttpContext.Current.Session[sessionName] = value;

protected internal static T Get<T>(string sessionName)
    return (T)HttpContext.Current.Session[sessionName];

public static int? WhatEverSessionVariableYouWantToHold
        return Get<int?>(nameof(WhatEverSessionVariableYouWantToHold));
        Save(nameof(WhatEverSessionVariableYouWantToHold), value);


Here is the implementation:

SessionCentralized.WhatEverSessionVariableYouWantToHold = id;

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x