如何在 ASP.NET Core 配置请求超时中间件

写在前面

本文参考官方文档,使用Asp.net core 8.0 的最小API 模板项目,配置超时中间件。

超时中间件可用于所有类型的ASP.NET Core应用:最小 API、带控制器的 Web API、MVC 和 Razor Pages。请求超时的属性位于命名空间 Microsoft.AspNetCore.Http.Timeouts 中。

需要注意的是,当应用在调试模式下运行时,超时中间件不会触发。要测试超时,请运行未附加调试器的应用。

代码实现

cs 复制代码
using Microsoft.AspNetCore.Http.Timeouts;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddRequestTimeouts();

var app = builder.Build();
app.UseRequestTimeouts();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.MapGet("/", async (HttpContext context) => {
    try
    {
        await Task.Delay(TimeSpan.FromSeconds(10), context.RequestAborted);
    }
    catch (TaskCanceledException)
    {
        return Results.Content("Timeout!", "text/plain");
    }

    return Results.Content("No timeout!", "text/plain");
}).WithRequestTimeout(TimeSpan.FromSeconds(2));
// Returns "Timeout!"

// 属性将终结点配置为超时
app.MapGet("/attribute",
    [RequestTimeout(milliseconds: 2000)] async (HttpContext context) => {
        try
        {
            await Task.Delay(TimeSpan.FromSeconds(10), context.RequestAborted);
        }
        catch (TaskCanceledException)
        {
            return Results.Content("Timeout!", "text/plain");
        }

        return Results.Content("No timeout!", "text/plain");
    });

app.Run();

调用示例

使用调试模式运行:

不会触发超时

非调试模式下运行

与预期一致触发了超时

相关推荐
皮皮林55121 分钟前
OpenFeign 首次调用卡 3 秒?八年老开发扒透 5 个坑,实战优化到 100ms!
后端
千寻girling2 小时前
《 Git 详细教程 》
前端·后端·面试
0xDevNull3 小时前
Linux 中 Nginx 代理 Redis 的详细教程
redis·后端
GetcharZp3 小时前
告别 Nginx 手动配置!这款 Go 语言开发的云原生网关,才是容器化时代的真香神器!
后端
RuoyiOffice3 小时前
SpringBoot+Vue3 企业考勤如何处理法定假期?节假日方案、调休补班与工作日判断链路拆解
spring boot·后端·vue·anti-design-vue·ruoyioffice·假期·人力
Vane14 小时前
从零开发一个AI插件,经历了什么?
人工智能·后端
952364 小时前
SpringBoot统一功能处理
java·spring boot·后端
rleS IONS5 小时前
SpringBoot中自定义Starter
java·spring boot·后端
DevilSeagull5 小时前
MySQL(2) 客户端工具和建库
开发语言·数据库·后端·mysql·服务
TeDi TIVE6 小时前
springboot和springframework版本依赖关系
java·spring boot·后端