我有一个项目存储在HttpContext中:
HttpContext.Current.Items["myItem"] = "123";
我可以通过页面的任何方法访问这个问题。例如:
protected override void OnLoad(EventArgs e)
{
string l_myItemVal = HttpContext.Current.Items["myItem"] as string; // "123"
}
这很好用。
但是,当通过AJAX调用页面的一个Web方法时,这会失败:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string MyWebMethod()
{
string l_myItemVal = HttpContext.Current.Items["myItem"] as string; // NULL
}
异步调用的HttpContext是否与页面的HttpContext不同?
答案 0 :(得分:3)
HttpContext.Items仅在单个请求期间保留项。您的AJAX请求是第二个请求,并且拥有自己的Items
属性。
答案 1 :(得分:-1)
也许您需要启用会话状态才能使其工作:
[System.Web.Services.WebMethod(true)]