C# Minimal API:响应缓存
Source: Dev.to
响应缓存
响应缓存可以减少客户端或代理向 Web 服务器发出的请求次数,同时也降低了服务器生成响应所需的工作量。响应缓存通过响应头来设置。(Microsoft Docs)
响应缓存使用 Cache‑Control 头进行配置,该头允许在客户端或途中(例如代理)缓存响应。
Minimal API 中的响应缓存
在 ASP.NET Core MVC 中,响应缓存(response caching)通常通过 ResponseCache 特性结合 UseResponseCaching 中间件来配置,但这纯粹是 MVC 的概念。
对于 Minimal API,我们可以通过添加一个 端点过滤器(endpoint filter),在请求处理完毕后设置 Cache‑Control 头,从而实现类似的行为。
RouteHandlerBuilder 缓存扩展
下面的扩展方法提供了一种简便方式,将响应缓存应用到 Minimal API 端点。端点过滤器在端点处理完请求后运行,并使用指定的最大存活时间设置 Cache‑Control 头。
public static class HttpResponseCachingConfiguration
{
private const int TenMinutes = 60 * 10;
private const int Hour = 60 * 60;
public static RouteHandlerBuilder AddResponseCacheTenMinutesHeader(this RouteHandlerBuilder routeHandlerBuilder)
=> routeHandlerBuilder.AddResponseCacheHeader(TenMinutes);
public static RouteHandlerBuilder AddResponseCacheHourHeader(this RouteHandlerBuilder routeHandlerBuilder)
=> routeHandlerBuilder.AddResponseCacheHeader(Hour);
public static RouteHandlerBuilder AddResponseCacheHeader(this RouteHandlerBuilder routeHandlerBuilder, int maxAgeInSeconds)
=> routeHandlerBuilder.AddEndpointFilter(async (context, next) =>
{
if (context.HttpContext.Response.StatusCode == StatusCodes.Status200OK)
{
context.HttpContext.Response.Headers.CacheControl = $"public,max-age={maxAgeInSeconds}";
}
return await next(context);
});
}
使用扩展
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.AddResponseCacheHourHeader()
.WithName("GetWeatherForecast");
注意: 浏览器或代理的客户端缓存需要先启用缓存功能。缓存生效后,客户端或代理会在合适的情况下自动返回已缓存的响应。
重要提示: 不要对需要身份验证或针对特定用户的端点使用公共响应缓存。
何时使用
当响应是 静态的、公开的,且可以 安全地被浏览器或代理缓存 时,才适合使用响应缓存。