繁体   English   中英

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

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

我正在使用带有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'需要对象引用

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

HttpContext.Current您提供当前...好的,Http Context; 您可以从中访问:会话,请求,响应等

如果你没有改变线程,你可以使用HttpContext.Current.Session ,如jwwishart所示。

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

试试这个:

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

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

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

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

静态代码可以以相同的方式访问应用程序缓存

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM