【发布时间】:2013-08-21 21:42:58
【问题描述】:
我在 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 为空。
I've learned我可以使用闭包来解决我的问题:
var state = HttpContext.Current;
var task = Request.Content.ReadAsByteArrayAsync().ContinueWith(t => {
HttpContext.Current = state;
DoSomething(t.Result);
});
我想知道是否有更好的方法... Web API 不应该为此提供一些扩展吗?
【问题讨论】:
-
NHibernate 会话不是线程安全的,因此通过
HttpContext.Current = state;传递它可能会导致问题。
标签: nhibernate asynchronous asp.net-web-api httpcontext