如何从ASP.NET Web API中的异步方法引用HttpContext?

问题描述 投票:0回答:1

我正在使用Web API,该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来检索这些属性。但是,当从异步方法调用提供程序时,上下文为null,并且我们得到的null引用为异常。

我已经阅读了几篇文章,解决方案对我来说并不明显。我尝试在配置文件中设置以下内容:

<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

而且我已经确定要确定比.NET 4.5更高的版本(它使用4.6.1)。

[其他人似乎建议您可以使用HttpContext调用异步方法,但我不知道如何执行,并且宁愿不必在此链中等待的每个方法中都调用HttpContext。

我正在使用Web API,该API仅运行同步代码。我想使某些方法异步并运行一些并行任务。问题是,在使方法异步之后,...

c# asynchronous asp.net-web-api async-await httpcontext
1个回答
0
投票

您没有在实际使用异步方法的地方显示代码,但是我猜测您正在使用.ConfigureAwait(false)。有人到处撒.ConfigureAwait(false),但这不是那么简单。

© www.soinside.com 2019 - 2024. All rights reserved.