HttpContext.在异步回调中Current为null
本文关键字:Current null 回调 异步 HttpContext | 更新日期: 2023-09-27 18:11:17
试图在方法回调中访问HttpContext.Current
,以便我可以修改Session
变量,但是我收到HttpContext.Current
是null
的异常。当_anAgent
对象触发回调方法时,将异步触发回调方法。
在SO上看到类似的问题后,我仍然不确定这个问题的解决方案。
我的代码的简化版本如下:
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
。为什么是这种情况下,如果我继续,忽略异常,我仍然可以获得相同的SessionID
和Session
变量使用ajax返回的GetSessionVar()
方法。
我应该启用aspNetCompatibilityEnabled设置吗?
我应该创建某种异步模块处理程序吗?
这与集成/经典模式有关吗?
这是一个基于类的解决方案,目前在MVC5 (MVC6支持基于di的上下文)中适用于简单的情况。
using System.Threading;
using System.Web;
namespace SomeNamespace.Server.ServerCommon.Utility
{
/// <summary>
/// Preserve HttpContext.Current across async/await calls.
/// Usage: Set it at beginning of request and clear at end of request.
/// </summary>
static public class HttpContextProvider
{
/// <summary>
/// Property to help ensure a non-null HttpContext.Current.
/// Accessing the property will also set the original HttpContext.Current if it was null.
/// </summary>
static public HttpContext Current => HttpContext.Current ?? (HttpContext.Current = __httpContextAsyncLocal?.Value);
/// <summary>
/// MVC5 does not preserve HttpContext across async/await calls. This can be used as a fallback when it is null.
/// It is initialzed/cleared within BeginRequest()/EndRequest()
/// MVC6 may have resolved this issue since constructor DI can pass in an HttpContextAccessor.
/// </summary>
static private AsyncLocal<HttpContext> __httpContextAsyncLocal = new AsyncLocal<HttpContext>();
/// <summary>
/// Make the current HttpContext.Current available across async/await boundaries.
/// </summary>
static public void OnBeginRequest()
{
__httpContextAsyncLocal.Value = HttpContext.Current;
}
/// <summary>
/// Stops referencing the current httpcontext
/// </summary>
static public void OnEndRequest()
{
__httpContextAsyncLocal.Value = null;
}
}
}
要使用它,可以从Global.asax.cs:
public MvcApplication() // constructor
{
PreRequestHandlerExecute += new EventHandler(OnPreRequestHandlerExecute);
EndRequest += new EventHandler(OnEndRequest);
}
protected void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
HttpContextProvider.OnBeginRequest(); // preserves HttpContext.Current for use across async/await boundaries.
}
protected void OnEndRequest(object sender, EventArgs e)
{
HttpContextProvider.OnEndRequest();
}
然后可以用它来代替HttpContext。当前:
HttpContextProvider.Current
可能有问题,因为我目前不理解这个相关的答案。请发表评论。
参考:AsyncLocal(需要。net 4.6)
当使用线程或async
函数时,HttpContext.Current
不可用。
尝试使用:
HttpContext current;
if(HttpContext != null && HttpContext.Current != null)
{
current = HttpContext.Current;
}
else
{
current = this.CurrentContext;
//**OR** current = threadInstance.CurrentContext;
}
一旦你为current
设置了一个合适的实例,你的代码的其余部分是独立的,无论是从线程调用还是直接从WebRequest
。
请参阅下面的文章,了解为什么Session变量为空,以及
可能的解决方法http://adventuresdotnet.blogspot.com/2010/10/httpcontextcurrent-and-threads-with.html从文章中引用;
当前的
HttpContext
实际上是在线程本地存储,这解释了为什么子线程不能访问它
作为一个建议的工作围绕作者说
在子线程中传递对它的引用。在回调方法的" state "对象中包含对
HttpContext
的引用,然后您可以将其存储到该线程的HttpContext.Current