【发布时间】:2020-02-07 16:11:39
【问题描述】:
我正在开发一个纯同步代码运行的 Web API。 我想将某些方法异步并运行一些并行任务。 问题是,在将方法异步后,HttpContext.Current 变为 null,当它随后在异步方法中被引用时。
Web API 在某些控制器方法上有一个过滤器,看起来像这样:
public class AuthenticationTokenFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var email = // Get some stuff from the request and do some things with it.
var id = // Get some stuff from the request and do some things with it.
System.Web.HttpContext.Current.Items.Add("Property1", email);
System.Web.HttpContext.Current.Items.Add("Property2", id);
}
随后,一个名为 ContextProvider 之类的注入类将直接引用 HttpContext 来检索这些属性。但是,当从异步方法调用提供者时,上下文为空,我们得到一个空引用是异常的。
我已经阅读了几篇关于此的帖子,但解决方案对我来说并不明显。 我尝试在配置文件中设置以下内容:
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
并且我确保目标是高于 .NET 4.5 的版本(它使用 4.6.1)。
其他人似乎建议您可以使用 HttpContext 调用异步方法,但我不知道该怎么做,并且不想在此链中等待的每个方法中都调用 HttpContext。
【问题讨论】:
标签: c# asynchronous asp.net-web-api async-await httpcontext