如何在静态方法中获取会话变量的值?

时间:2010-04-05 06:24:38

标签: c# asp.net methods static session-variables

我正在使用带有jQuery的ASP.NET页面方法....如何在C#中的静态方法中获取会话变量的值?

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

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

当我编译它时,我收到错误:

  

非静态字段,方法或属性'System.Web.UI.Page.Session.get'`

需要对象引用

4 个答案:

答案 0 :(得分:96)

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

HttpContext.Current让你获得当前......好吧,Http Context;您可以从中访问:会话,请求,响应等

答案 1 :(得分:20)

如果您没有更改主题,可以使用HttpContext.Current.Session,如jwwishart所示。

HttpContext.Current返回与线程关联的上下文。显然,这意味着如果您已经启动了新线程,则无法使用它。您可能还需要考虑线程敏捷性 - ASP.NET请求并不总是在整个请求的同一线程上执行。我相信上下文是适当传播的,但是要记住这一点。

答案 2 :(得分:2)

试试这个:

HttpContext.Current.Session["UserName"].ToString();

答案 3 :(得分:1)

您可以通过HttpContext.Current - static 属性访问当前Session,通过该属性,您可以检索适用于当前网络请求的HttpContext实例。这是静态应用程序代码和静态页面方法中的常见模式。

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

使用相同的技术从Session装饰的ASMX Web方法中访问[WebMethod(EnableSession = true)],因为虽然这些方法不是静态的,但它们不会从Page继承,因此没有直接访问Session属性。

静态代码可以以相同的方式访问Application Cache

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

如果静态代码在另一个项目中,我们需要引用System.Web.dll。但是,在这种情况下,通常最好避免这种依赖,因为如果从ASP.NET上下文调用代码HttpContext.Current将是null,那么显而易见原因。相反,我们可以要求HttpSessionState作为参数(当然我们仍需要引用System.Web):

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

呼叫:

[WebMethod]
public static string GetName()
{
    return SomeLibraryClass.SomeLibraryFunction(HttpContext.Current.Session);
}