HttpContext 仅在 ASP.NET Core 管道中存在活动 HTTP 请求时有效。整个 ASP.NET Core 管道是执行每个请求的异步委托链。从此链返回的 Task 完成后,会回收 HttpContext。
请勿这样做:下面的示例使用 ,它使 HTTP 请求在达到第一个 await 时完成:.
-
这在 ASP.NET Core 应用中始终是不良做法。
-
在 HTTP 请求完成之后访问 HttpResponse。
-
使进程崩溃。
public class AsyncBadVoidController : Controller
{
[HttpGet("/async")]
public async void Get()
{
await Task.Delay(1000);
// The following line will crash the process because of writing after the
// response has completed on a background thread. Notice async void Get()
await Response.WriteAsync("Hello World");
}
}
请这样做:下面的示例将 返回到框架,因此在操作完成之前,HTTP 请求不会完成。
public class AsyncGoodTaskController : Controller
{
[HttpGet("/async")]
public async Task Get()
{
await Task.Delay(1000);
await Response.WriteAsync("Hello World");
}
}