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'`
Try this:
You can access the current
Session
viaHttpContext.Current
- a static property through which you can retrieve theHttpContext
instance that applies to the current web request. This is a common pattern in static App Code and static page methods.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 fromPage
and thus do not have direct access to aSession
property.Static code can access the Application Cache in the same way:
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 contextHttpContext.Current
will benull
, for obvious reasons. Instead, we can require aHttpSessionState
as an argument (we'll still need the reference toSystem.Web
of course):Call:
HttpContext.Current.Session["..."]
HttpContext.Current
gets you the current ... well, Http Context; from which you can access: Session, Request, Response etcIf 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.