How to preserve HttpContext in Web API async task
I have an action in a Web API Controller that reads bytes async:
public HttpResponseMessage Post() {
var response = Request.CreateResponse(HttpStatusCode.Created);
var task = Request.Content.ReadAsByteArrayAsync().ContinueWith(t => {
DoSomething(t.Result);
});
task.Wait();
return response;
}
In my DoSomething method, I need access to HttpContext, e.g, using
NHibernate's WebSessionContext. Unfortunately, HttpContext.Current is
null.
I've learned I can use a closure to solve my problem:
var state = HttpContext.Current;
var task = Request.Content.ReadAsByteArrayAsync().ContinueWith(t => {
HttpContext.Current = state;
DoSomething(t.Result);
});
I wonder if there is a better way... shouldn't Web API have some
extensions for this?
No comments:
Post a Comment