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

标签 c# asp.net-mvc asp.net-mvc-3 asynchronous async-await

我有以下 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/

相关文章:

c# - winforms - 状态栏标签的工具提示未显示

c# - 获取多个JSON数据

c# - `IDictionary<String, String>` 方法中类型为 `EventListener.EnableEvents` 的最后一个参数的目的是什么?

asp.net-mvc - 模型绑定(bind)下拉选择值

asp.net-mvc-3 - 找不到支持服务 System.Web.Mvc.IControllerFactory 的组件

C# 数组访问与 C++ PInvoke 指针访问

asp.net-mvc - 如何将SQL表数据导入Redis缓存?

asp.net - jQuery Mobile 方向 ASP.NET 或 MVC

c# - 在 Controller 的 MVC **外部**中模拟 HttpContext

c# - mvc3 应用程序中的 RDLC 报告