ASP.NET Core 中的输出缓存如何配置?

来源:这里教程网 时间:2026-02-21 17:28:04 作者:

ASP.NET Core 中的输出缓存通过 Output Caching 中间件实现,主要用于缓存整个 HTTP 响应内容,提升性能。从 ASP.NET Core 7 开始,官方引入了统一的输出缓存机制,取代了旧版中功能有限的

[OutputCache]
特性。

启用输出缓存服务

Program.cs 中注册输出缓存服务:

调用
AddOutputCache()
添加缓存服务
使用
UseOutputCache()
启用中间件
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOutputCache();

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

配置缓存策略

可以定义命名策略或基于规则的方式控制缓存行为。

全局策略:对所有端点生效 命名策略:按名称引用,灵活分配给特定路由或控制器 匿名策略:直接应用于某个终结点

示例:定义一个缓存 60 秒的命名策略

builder.Services.AddOutputCache(options =>
{
options.AddPolicy("Default", context => context.Expire(TimeSpan.FromSeconds(60)));
});

在终结点上应用缓存

有多种方式将缓存策略绑定到具体请求处理逻辑。

Minimal API 中使用 app.MapGet("/time", () => DateTime.Now.ToString())
.CacheOutput("Default");
控制器中使用特性 [ApiController]
[Route("[controller]")]
public class TimeController : ControllerBase
{
[HttpGet]
[OutputCache(PolicyName = "Default")]
public IActionResult Get() => Ok(DateTime.Now);
}

自定义缓存条件

可基于请求头、查询参数、路径等决定是否参与缓存。

例如:仅当用户未登录且请求为 GET 时缓存

options.AddPolicy("AnonymousGet", context =>
{
var isGet = context.HttpContext.Request.Method == "GET";
var isAuthenticated = context.HttpContext.User.Identity?.IsAuthenticated == true;
if (!isGet || isAuthenticated)
{
context.NoCache();
}
else
{
context.Expire(TimeSpan.FromMinutes(5));
}
});

该机制支持细粒度控制,比如排除某些查询参数、设置 vary headers(如 Vary by Query Keys、Vary by Header)等。

常见配置选项

Expire(TimeSpan)
:设置过期时间
VaryByQueryKeys(new[] {"id"})
:根据查询参数变化缓存
VaryByHeader("Accept-Language")
:根据请求头区分缓存版本
NoCache()
:跳过缓存

例如:根据不同地区语言缓存不同版本

options.AddPolicy("Localized", context =>
{
context.VaryByHeader("Accept-Language")
.Expire(TimeSpan.FromHours(1));
});
基本上就这些。合理配置输出缓存能显著减少服务器负载,加快响应速度。注意避免对个性化内容误用缓存。

相关推荐