HttpContext.Current
以便修改Session
变量,但是我收到了异常,提示HttpContext.Current
为null
。当_anAgent
对象触发它时,回调方法会异步启动。在查看SO上的similar questions后,我仍然不确定解决方案。
我的代码简化版本如下:
public partial class Index : System.Web.UI.Page
protected void Page_Load()
{
// aCallback is an Action<string>, triggered when a callback is received
_anAgent = new WorkAgent(...,
aCallback: Callback);
...
HttpContext.Current.Session["str_var"] = _someStrVariable;
}
protected void SendData() // Called on button click
{
...
var some_str_variable = HttpContext.Current.Session["str_var"];
// The agent sends a message to another server and waits for a call back
// which triggers a method, asynchronously.
_anAgent.DispatchMessage(some_str_variable, some_string_event)
}
// This method is triggered by the _webAgent
protected void Callback(string aStr)
{
// ** This culprit throws the null exception **
HttpContext.Current.Session["str_var"] = aStr;
}
[WebMethod(EnableSession = true)]
public static string GetSessionVar()
{
return HttpContext.Current.Session["str_var"]
}
}
我不确定是否必要,但我的WorkAgent
类看起来像这样:
public class WorkAgent
{
public Action<string> OnCallbackReceived { get; private set; }
public WorkAgent(...,
Action<string> aCallback = null)
{
...
OnCallbackReceived = aCallback;
}
...
// This method is triggered when a response is received from another server
public BackendReceived(...)
{
...
OnCallbackReceived(some_string);
}
}
代码的作用:
点击一个按钮会调用SendData()
方法,在此方法内,_webAgent
将消息分派到另一个服务器并等待回复(此时用户仍然可以与该页面交互并引用相同的SessionID
)。一旦接收到回复,它就会调用BackendReceived()
方法,然后在.aspx.cs页面中调用Callback()
方法。
问题:
当WorkAgent
触发Callback()
方法时,它尝试访问HttpContext.Current
,但是它为null
。如果我忽略异常继续进行,为什么我仍然可以使用ajax返回的GetSessionVar()
方法获取相同的SessionID
和Session
变量?
我是否应该启用aspNetCompatibilityEnabled设置?
我是否应该创建某种异步模块处理程序?
这是否与集成/经典模式有关?
SendData()
。这将数据发送到其他服务器。我只是困惑为什么回调时HttpContect.Current
变成了null。 - Serge P