Nhibernate 如何在Web API异步任务中保留HttpContext

Nhibernate 如何在Web API异步任务中保留HttpContext,nhibernate,asynchronous,asp.net-web-api,httpcontext,Nhibernate,Asynchronous,Asp.net Web Api,Httpcontext,我在Web API控制器中有一个异步读取字节的操作: public HttpResponseMessage Post() { var response = Request.CreateResponse(HttpStatusCode.Created); var task = Request.Content.ReadAsByteArrayAsync().ContinueWith(t => { DoSomething(t.Result); });

我在Web API控制器中有一个异步读取字节的操作:

public HttpResponseMessage Post() {
    var response = Request.CreateResponse(HttpStatusCode.Created);
    var task = Request.Content.ReadAsByteArrayAsync().ContinueWith(t => {
        DoSomething(t.Result);
    });
    task.Wait();
    return response;
}
在我的DoSomething方法中,我需要访问HttpContext,例如,使用NHibernate的WebSessionContext。不幸的是,HttpContext.Current为null

我可以使用闭包来解决我的问题:

var state = HttpContext.Current;
var task = Request.Content.ReadAsByteArrayAsync().ContinueWith(t => {
    HttpContext.Current = state;
    DoSomething(t.Result);
});

我想知道是否有更好的方法。。。Web API不应该对此进行一些扩展吗?

尝试使您的操作异步:

public async Task<HttpResponseMessage> Post() 
{
    byte[] t = await Request.Content.ReadAsByteArrayAsync();

    DoSomething(t);

    // You could safely use HttpContext.Current here 
    // even if this is a terribly bad practice to do.
    // In a properly designed application you never need to access 
    // HttpContext.Current directly but rather work with the abstractions 
    // that the underlying framework is offering to you to access whatever
    // information you are trying to access.

    // Bear in mind that from reusability and unit restability point of view,
    // code that relies on HttpContext.Current directly is garbage.

    return Request.CreateResponse(HttpStatusCode.Created);
}
public async Task Post()
{
字节[]t=wait Request.Content.ReadAsByteArrayAsync();
剂量测定法(t);
//您可以在此处安全地使用HttpContext.Current
//即使这是一个非常糟糕的做法。
//在正确设计的应用程序中,您永远不需要访问
//HttpContext.Current可以直接使用,但可以使用抽象
//底层框架提供给您访问任何
//您试图访问的信息。
//请记住,从可重用性和单元可重启性的角度来看,
//直接依赖HttpContext.Current的代码是垃圾。
返回请求.CreateResponse(HttpStatusCode.Created);
}

我这样做是因为我想在我的任务中使用NHibernate的“WebSessionContext”,它使用HttpContext.Current内部。。。感谢您指出out.NHibernate会话不是线程安全的,因此通过
HttpContext.Current=state传递它可能会导致问题。