【发布时间】:2018-07-27 20:09:33
【问题描述】:
我有一个使用 WCF REST 在 IIS 中运行的 ASP.NET 应用程序。
我需要为当前的 HTTP 请求存储变量,为此我使用 HttpContext.Current.Items。我存储了一些我在global.asax 中设置的请求 ID,以便我可以在我的服务中更深入地使用它。我的服务正在执行一些 I/O 操作,因此我最近将它们从同步更改为异步。问题是在第一个await 之后,HttpContext.Current 变为空,因此我无法访问存储在HttpContext.Current.Items 中的变量。
我的 global.asax:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Items["CurrentRequestId"] = SetRequestId();
}
我的 WCF 合同:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class WcfService
{
[OperationContract]
[WebGet(UriTemplate = "Operation")]
public async Task<bool> Operation()
{
var context = HttpContext.Current; // Current context available here
await Task.Delay(1000).ConfigureAwait(true); // tried with both ConfigureAwait(true) and ConfigureAwait(false)
context = HttpContext.Current; // Current context is always null here
return true;
}
}
我试图在我的 web.config 文件中添加这些键,但它没有改变任何东西。
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
<add key="wcf:disableOperationContextAsyncFlow" value="false"/>
</appSettings>
我正在使用 .net 4.6.2
<httpRuntime targetFramework="4.6.2" />
在使用 ASP.NET 在 WCF REST 中等待异步方法后,是否可以保留 HttpContext.Current?我可以用HttpContext.Current.Items 的替代方法来实现我想要做的事情吗?
编辑: 这是一个简化的示例,但 HttpContext.Current 使用得更深,我不希望在等待之前收集它并将其一直传递给每个方法.
【问题讨论】:
-
在等待之后使用你的
context -
你有没有找到解决这个问题的方法?
-
@Bouke 我迁移到了 ASP.NET Core,所以不再有这个问题,但如果我没记错的话,我必须使用
AsyncLocal而不是依赖于HttpContext.Current.
标签: c# asp.net wcf asynchronous async-await