views:

7367

answers:

5

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

+16  A: 

Access the Session via the threads HttpContext:-

HttpContext.Current.Session["loginId"]
AnthonyWJones
+24  A: 

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

public class MySession
{
    // private constructor
    private MySession() {}

    // 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
M4N
Hi, we have to write code for get and set, right? "public int LoginId { get; set; }"
Prashant
I have written it like: get { return Convert.ToString(HttpContext.Current.Session["webm_login"]); } set { HttpContext.Current.Session["webm_login"] = value; }
Prashant
Is it correct way for get and set ???
Prashant
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
When I am using your method, property without any definition then its giving me "CS0501: 'ItsSession.webm_login.get' must declare a body because it is not marked abstract or extern"
Prashant
Please tell me why its creating problem.
Prashant
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
Ok, so that means automatic properties are available in .net 3.x . I am using 2.x may be that's why automatic properties are not working. Thanks
Prashant
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.
Prashant
Marked as answer.....
Prashant
@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.
Brandon Boone
Thanks @Brandon Boone. Reputation is not everything - but of course nobody stops you from upvoting some of my other answers, if you think they are any good ;-)
M4N
+4  A: 

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.

Cerebrus
A: 

Martin - excellent solution. It helped me a lot. Many Thanks

MSIL
Glad it helped you!
M4N
But the solution is not working at my end, @MSIL can u please let me know how you done this...
Prashant
Hi Prashant - have you created the file for this class under APP_Code folder (thats the only place it will work from)? I have used the same code as above and only edited/added some fields to it. As this class has static properties - it is acccessible from any page in the web application
MSIL
+1  A: 

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.

Ernie