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

ACP picture ACP · Apr 5, 2010 · Viewed 88.3k times · Source

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'`

Answer

jwwishart picture jwwishart · Apr 5, 2010

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

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