3

我在 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 为空。

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

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

我想知道是否有更好的方法...... Web API 不应该为此提供一些扩展吗?

4

1 回答 1

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);
}
于 2013-08-21T22:16:19.053 回答