You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET 6 Minimal APIs中实现响应缓存?

.NET 6 Minimal API 响应缓存优雅实现方案

你之前熟悉的MVC控制器响应缓存方案,在Minimal API中也有对应的原生实现,无需手动拼接cache-control响应头,步骤如下:

步骤1:注册服务与中间件

首先在Program.cs中完成基础配置:

  1. 注册响应缓存服务:
builder.Services.AddResponseCaching();
  1. 在路由匹配之后、业务端点执行之前添加响应缓存中间件:
var app = builder.Build();

// 其他中间件,例如UseHttpsRedirection、UseCors等
app.UseRouting();
// 响应缓存中间件需放在此处
app.UseResponseCaching();
app.UseAuthorization();

// 端点定义位置
app.MapGet("/test", () => "hello world");

app.Run();

步骤2:给端点配置缓存规则

两种常用实现方式,都和MVC的[ResponseCache]特性逻辑完全对齐:

方式1:直接添加ResponseCache元数据

app.MapGet("/weatherforecast", () =>
{
    return new WeatherForecast(DateTime.Now, 25, "Sunny");
})
// 等价于MVC控制器上添加[ResponseCache(Duration = 10)]
.WithMetadata(new ResponseCacheAttribute 
{ 
    Duration = 10,
    Location = ResponseCacheLocation.Any,
    NoStore = false
});

方式2:封装扩展方法简化调用

如果多个端点需要复用缓存规则,可以封装扩展方法,使用体验和MVC加特性几乎一致:

// 定义扩展方法
public static class RouteHandlerCacheExtensions
{
    public static RouteHandlerBuilder CacheFor(this RouteHandlerBuilder builder, int seconds)
    {
        return builder.WithMetadata(new ResponseCacheAttribute { Duration = seconds });
    }
}

// 使用时直接链式调用即可
app.MapGet("/weatherforecast", () => new WeatherForecast(DateTime.Now, 25, "Sunny"))
    .CacheFor(10);

注意事项

  • 仅GET、HEAD类型的请求,且响应状态码为200时才会触发缓存
  • 如果请求携带Authorization头,需要显式设置Location = ResponseCacheLocation.Public才会生效
  • 如需配置全局缓存规则(如最大缓存体大小、默认过期时间等),可在服务注册时修改配置:
builder.Services.AddResponseCaching(options =>
{
    // 单条响应最大缓存大小,默认64MB
    options.MaximumBodySize = 32 * 1024 * 1024;
    // 未指定Duration时的默认过期时间
    options.DefaultExpirationTimeSpan = TimeSpan.FromSeconds(10);
});

内容的提问来源于stack exchange,提问作者konkri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:18:03