gpt4 book ai didi

c# - 在异步任务中使用 HttpContext

转载 作者:可可西里 更新时间:2023-11-01 07:57:13 28 4
gpt4 key购买 nike

我有以下 mvc 操作。

public async Task<JsonResult> DoSomeLongRunningOperation()
{
return await Task.Run(() =>
{
//Do a lot of long running stuff
//The underlying framework uses the HttpContext.Current.User.Identity.Name so the user is passed on the messagebus.
}
}

在任务中,HttpContext 变为空。我们做了很多欺骗,但没有任何东西可以确保 HttpContext 在我们的新线程中始终可用。

是否有在异步任务中使用 HttpContext 的解决方案?

在我们的 IocContainer 中,我们注册了以下将用户名传递给框架的对象。

public class HttpContextUserIdentityName : ICredentials
{
public string Name
{
get { return HttpContext.Current.User.Identity.Name; }
}
}

这段代码在持久化到数据库之前在很多地方被调用。

我们需要另一种方法来获取发起网络请求的用户的用户名,或者解决 HttpContext 为空的问题。

因为持久化到数据库发生在任务中,所以在进入任务之前我无法访问 HttpContext。

我也想不出一种安全的方法来临时保留用户名,以便我可以实现另一个 ICredentials 服务对象。

最佳答案

您几乎不想在 ASP.NET 方法中使用 Task.Run

我认为最干净的解决方案(但也是最有效的)是在其他层实现 async 兼容的接口(interface):

public async Task<JsonResult> DoSomeLongRunningOperation()
{
//Do a lot of long running stuff
var intermediateResult = await DoLongRunningStuff();
return await DetermineFinalResult(intermediateResult);
}

关于c# - 在异步任务中使用 HttpContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13748267/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com