如何在 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();

调用示例

使用调试模式运行:

不会触发超时

非调试模式下运行

与预期一致触发了超时

相关推荐
rannn_11121 分钟前
【苍穹外卖|Day4】套餐页面开发(新增套餐、分页查询、删除套餐、修改套餐、起售停售)
java·spring boot·后端·学习
短剑重铸之日31 分钟前
《设计模式》第十一篇:总结
java·后端·设计模式·总结
Dragon Wu1 小时前
Spring Security Oauth2.1 授权码模式实现前后端分离的方案
java·spring boot·后端·spring cloud·springboot·springcloud
一个有梦有戏的人2 小时前
Python3基础:进阶基础,筑牢编程底层能力
后端·python
爬山算法2 小时前
Hibernate(88)如何在负载测试中使用Hibernate?
java·后端·hibernate
独断万古他化2 小时前
【Spring 原理】Bean 的作用域与生命周期
java·后端·spring
我爱加班、、3 小时前
Websocket能携带token过去后端吗
前端·后端·websocket
一 乐3 小时前
校园二手交易|基于springboot + vue校园二手交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
80530单词突击赢3 小时前
SpringBoot整合SpringMVC全解析
java·spring boot·后端
hdsoft_huge3 小时前
1panel面板中部署SpringBoot和Vue前后端分离系统 【图文教程】
vue.js·spring boot·后端