67

I am using ASP.NET page methods with jQuery.... How do I get the value of a session variable inside a static method in C#?

protected void Page_Load(object sender, EventArgs e)
{
    Session["UserName"] = "Pandiya";
}

[WebMethod]
public static string GetName()
{
    string s = Session["UserName"].ToString();
    return s;
}

When I compile this I get the error:

An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Session.get'`

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
ACP
  • 34,682
  • 100
  • 231
  • 371

4 Answers4

111

HttpContext.Current.Session["..."]

HttpContext.Current gets you the current ... well, Http Context; from which you can access: Session, Request, Response etc

Himanshu
  • 31,810
  • 31
  • 111
  • 133
jwwishart
  • 2,865
  • 2
  • 23
  • 26
  • 2
    HttpContext.Current gives you access to the current Http Context as explained in the edit i just did. The HttpContext.Current property is static (http://msdn.microsoft.com/en-us/library/system.web.httpcontext_members.aspx) and it does it's magic and returns you the current HttpContext. You should have access to most of the stuff you have access in the code behind etc. – jwwishart Apr 05 '10 at 06:33
  • P.S. You were trying to access a non-static property (Session property) via a static method... obviously it(the Session property) exists only on an instance of the class! Hope this explains things better? – jwwishart Apr 05 '10 at 06:35
  • 7
    @Pandiya Chendur: `Session` is a instance property of the Page class that returns an `HttpSessionState` object. When you write something like `Session["..."]`, this is really `this.Session["..."]`. Because a static member has no `this` object, you can't access the `Session` property. You can, however, access the same `HttpSessionState` object using the code that hwwishart suggested. – P Daddy Apr 05 '10 at 06:36
  • 1
    @jwwishart: Sorry for mistyping your name in the previous comment. J and H are right next to each other and the room is dark at the moment. – P Daddy Apr 05 '10 at 06:43
  • How can we use the Page, Application etc in static method, – Raghav Sep 12 '11 at 13:33
  • This is not working for me. I can get the HttpContext.Current.Session in debugger watch window, but it does not have the session variable that was made on another page. It has the same session id though. I am also using a static web method too - which is where I need it. – John Foll Apr 03 '23 at 16:59
21

If you haven't changed thread, you can use HttpContext.Current.Session, as indicated by jwwishart.

HttpContext.Current returns the context associated with the thread. Obviously this means you can't use it if you've started a new thread, for example. You may also need to consider thread agility - ASP.NET requests don't always execute on the same thread for the whole of the request. I believe that the context is propagated appropriately, but it's something to bear in mind.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • SessionState works with page methods and I believe your concerns are not valid Jon (other than if a new thread is started by our own code, I don't know what happens then). I'd be more nervous of your unqualified suggestion that "Ideally you should pass all the information you need from the client instead" as that very much depends on the nature of the data - I have seen some very [dangerous examples](https://stackoverflow.com/a/30683127/397817) in the wild! I'd rather say "it depends". – Stephen Kennedy Mar 11 '18 at 11:13
  • @StephenKennedy: I've removed the last paragraph entirely rather than spending ages adding nuance for a nearly-8-year-old answer. – Jon Skeet Mar 11 '18 at 12:14
4

Try this:

HttpContext.Current.Session["UserName"].ToString();
Muhammad Awais
  • 4,238
  • 1
  • 42
  • 37
2

You can access the current Session via HttpContext.Current - a static property through which you can retrieve the HttpContext instance that applies to the current web request. This is a common pattern in static App Code and static page methods.

string s = (string)HttpContext.Current.Session["UserName"];

The same technique is used to access the Session from within ASMX web methods decorated with [WebMethod(EnableSession = true)] because whilst such methods are not static they do not inherit from Page and thus do not have direct access to a Session property.

Static code can access the Application Cache in the same way:

string var1 = (string)HttpContext.Current.Cache["Var1"];

If the static code is inside another project we need to reference System.Web.dll. However, in this case it is generally best to avoid such a dependency because if the code is called from outside of an ASP.NET context HttpContext.Current will be null, for obvious reasons. Instead, we can require a HttpSessionState as an argument (we'll still need the reference to System.Web of course):

public static class SomeLibraryClass
{
    public static string SomeLibraryFunction(HttpSessionState session)
    {
       ...
    }
}

Call:

[WebMethod]
public static string GetName()
{
    return SomeLibraryClass.SomeLibraryFunction(HttpContext.Current.Session);
}
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108