【发布时间】:2014-08-24 00:29:55
【问题描述】:
尝试在方法回调中访问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 设置吗?
我应该创建某种asynchronous module handler 吗?
这与Integrated/Classic mode 有关吗?
【问题讨论】:
-
为什么要使用回调来复杂化这个问题,更好的解决方案可能是从客户端使用 ajax,这样用户仍然可以与网站交互。而对其他系统的调用可以只是普通的方法调用
-
Ajax 大部分是从客户端使用的,只是没有将它包含在上面的代码中(它更新了
HttpContext Session变量和SQL 数据库)。唯一不是 ajax 调用的方法是SendData()。这会将数据发送到其他一些服务器。我只是很困惑为什么HttpContect.Current在回调中变为 null。 -
请查看我的回答,了解为什么会发生这种情况
标签: c# asp.net .net wcf asynchronous