How can I get the value of a session variable inside a static method?

I am using asp.net pagemethods with jQuery .... How to 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 an error:

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

Any suggestion or any alternative?

+51
methods c # static session-variables
Apr 05 '10 at 6:24
source share
3 answers

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

HttpContext.Current gets the current ... well, Http Context; from which you can access: session, request, response, etc.

+82
Apr 05 '10 at 6:26
source share

If you have not changed the thread, you can use HttpContext.Current.Session , as indicated in the jwwishart file.

HttpContext.Current returns the context associated with the stream. Obviously, this means that you cannot use it, for example, if you started a new thread. You may also need to consider thread flexibility β€” ASP.NET requests are not always executed on the same thread for the entire request. I believe the context is promoted appropriately, but there is something to keep in mind.

On the other hand, I'm not sure if you even have a session for the AJAX page method. You can try, but I would be a little nervous about it. Ideally, you should pass on all the information you need from the client.

+16
Apr 05 2018-10-10T00:
source share

Try the following:

 HttpContext.Current.Session["UserName"].ToString(); 
+2
Jun 11 '16 at 16:00
source share



All Articles