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

时间:2013-08-21 21:42:59

标签: nhibernate asynchronous asp.net-web-api httpcontext

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

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。

I've learned我可以使用闭包来解决我的问题:

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

我想知道是否有更好的方法...... Web API是否应该有一些扩展呢?

1 个答案:

答案 0 :(得分:4)

尝试使您的操作异步:

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);
}