167

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

Session["loginId"]

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

Session["loginId"]

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#)

7 Answers 7

374

(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
    {
      get
      {
        MySession session =
          (MySession)HttpContext.Current.Session["__MySession__"];
        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)
20
  • 6
    There's no need to write any code, use as shown in the answer. E.g. "public int LoginId { get; set; }" --> this is called an automatic property.
    – M4N
    Apr 7, 2009 at 13:00
  • 4
    If you are using .net 3.x you can use automatic properties as shown in my code. With .net 2.x/1.x this is not available and you have to implement the getter/setter of your properties yourself: private int _loginId; public int LoginId { get { return _loginId; } set { _loginId = value; } }
    – M4N
    May 2, 2009 at 15:56
  • 2
    Looks cool now, I think i got the answer of my problem, and I am alreday using your way, its very clean and easy to maintain all my session variables at one place. Thanks @Martin, you are AWESOME.
    – djmzfKnm
    Jun 8, 2009 at 4:53
  • 23
    @M4N, Wish I could express a bit more gratitude than a +1. This has become my favorite way of dealing with the session/cache in my projects. My code, literally, is thanking you. Aug 28, 2010 at 14:13
  • 4
    @Kristopher while the 'Current' property is static the instance of MySession returned is not...so it's fine. Static methods and properties are safe to use in this way.
    – Darren
    Nov 12, 2015 at 22:52
113

Access the Session via the thread's HttpContext:-

HttpContext.Current.Session["loginId"]
5
  • Thanks a ton Anthony for this simple step.
    – Kings
    Mar 22, 2012 at 15:04
  • Thanks a lot Anthony ,+1 for that Jun 7, 2012 at 15:12
  • Thanks. Forgot what the namespace was :) Nov 17, 2014 at 7:18
  • @AnthonyWJones i used your method, but have problem, can you explain me, where i am wrong or what is proper way to use, my question stackoverflow.com/questions/45254279/…
    – adnan
    Jul 24, 2017 at 5:23
  • and if you want to convert to HttpSessionStateBase: HttpSessionStateBase session = new HttpSessionStateWrapper(HttpContext.Current.Session); re: stackoverflow.com/questions/5447611/…
    – sobelito
    Oct 26, 2019 at 6:17
24

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.

2
  • 4
    +1 for brining this up. If you are not using InProc for Session, then Ernie is 100% correct. InProc is very limited anyway, as it does not support webfarms and will be lost if the application re-starts. Note, by performance cost we are looking at a 20% premium in using State Server mode, and serialization costs are added on top of that. As you can imagine this can get expensive. You can avoid some of the serialization overhead by sticking to primitive types (e.g. int, string, char, byte, etc.). Custom objects will be faced with serialization. User beware. Aug 16, 2012 at 22:37
  • +1 Good point. A change that would marry the two concepts would be to have each property on this custom "session" class call the asp.net session itself instead of one big object in session. Have to do the type casting that @M4N's approach avoids, but maybe worth it if you only read some of session each time.
    – eol
    Dec 13, 2013 at 14:12
12

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.

1
  • That's great explanation,it helped me +1 for that :) Jun 7, 2012 at 17:24
3

In asp.net 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");
    }
}

Source: https://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/

1

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.

MA

0

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
{
    get
    {
        return Get<int?>(nameof(WhatEverSessionVariableYouWantToHold));
    }
    set
    {
        Save(nameof(WhatEverSessionVariableYouWantToHold), value);
    }
}

}

Here is the implementation:

SessionCentralized.WhatEverSessionVariableYouWantToHold = id;

Not the answer you're looking for? Browse other questions tagged or ask your own question.