在异步任务使用的HttpContext [英] Using HttpContext in Async Task

查看:178
本文介绍了在异步任务使用的HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下MVC的行动。

I have the following mvc action.

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的是在我们的新线程可用的始终。

In the task the HttpContext gets null. We did a lot of tricking, but nothing assures us of the HttpContext being available always in our new thread.

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

Is there a solution to use HttpContext within out async tasks?

在我们的Io​​cContainer,我们已经注册了以下对象,将用户名的框架。

In our IocContainer we have registered the following object which passes the username to the framework.

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

这code是坚持到数据库之前叫了很多地方。

This code is called in a lot of places before persisting to the database.

我们需要或者获得用户的用户名的另一种方式发起的WebRequest或修复这个问题HttpContext的是NULL。

We need either another way of getting the username of the user initiated the webrequest or fix the issue with the HttpContext being null.

由于持续存在到数据库中的任务发生了,我无法访问的HttpContext进入任务前。

Because the persisting to the database happens in the Task I can't access the HttpContext before entering the task.

我也想不出一个安全的方式来坚持临时的用户名,所以我可以实现另一个ICredentials服务对象。

I also can't think of a safe way to temporary persist the username so I can implement another ICredentials service object.

推荐答案

您几乎从来没有想要在一个ASP.NET的方法来使用 Task.Run

You almost never want to use Task.Run in an ASP.NET method.

我觉得干净的解决方案(但最多的工作)是贯彻落实异步你的其他层兼容接口:

I think the cleanest solution (but the most work) is to implement async-compatible interfaces at your other layers:

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

这篇关于在异步任务使用的HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆