我在 IIS 10 中托管了 ASP.NET Core Web API 6。由于对 API 的请求数量巨大,API 生成了超时错误。
超时后如何取消请求?问题是,即使超时后,工作处理器仍会处理请求。超时后如何取消工作处理器请求?
提前致谢
您可以在控制器操作中使用 HttpContext 类的 RequestAborted 属性。该属性返回一个 CancellationToken,当客户端断开连接或请求超时时触发。您可以将此令牌传递给任何支持取消的异步方法,例如 Task.Delay 或 HttpClient.SendAsync。这样,您可以取消请求处理并释放工作处理器资源。例如,您可以使用以下代码:
[HttpGet]
public async Task<ActionResult<string>> Get()
{
// Get the cancellation token from the request context
var cancellation = HttpContext.RequestAborted;
// Pass the token to any async methods that support cancellation
await database.FooAsync(cancellation);
// Return the result
return Ok("No timeout!");
}
另一个解决方案是在终结点路由中使用 Microsoft.AspNetCore.Http 命名空间中的 WithRequestTimeout 扩展方法。此方法允许您为每个端点指定自定义超时策略,并且可以选择在发生超时时返回自定义响应。这样,您可以取消请求处理并释放工作处理器资源。例如,您可以使用以下代码:
app.MapGet("/usepolicy", async (HttpContext context) =>
{
try
{
// Do some long running operation
await Task.Delay(TimeSpan.FromSeconds(10), context.RequestAborted);
}
catch (TaskCanceledException)
{
throw;
}
return Results.Content("No timeout!", "text/plain");
}).WithRequestTimeout(TimeSpan.FromSeconds(5)); // Specify the timeout policy
如果不需要考虑其他因素,回收App Pool是最简单的方法。