gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:48:12 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

尝试让你的 Action 异步:

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

关于nhibernate - 如何在 Web API 异步任务中保留 HttpContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18368209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com