根据this页面,我应该启用响应缓存中间件以在端点上使用
ResponseCache
属性。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddResponseCaching(); // <--- here
var app = builder.Build();
app.UseHttpsRedirection();
// UseCors must be called before UseResponseCaching
//app.UseCors();
app.UseResponseCaching(); // <--- here
app.UseAuthorization();
app.MapControllers();
app.Run();
我只将
ResponseCache
属性添加到我的控制器端点,但忘记添加上述行来启用和配置响应缓存中间件。但是,端点确实返回了正确的缓存配置。
我是否误解了页面中的文字,或者此功能现在默认启用?
[ResponseCache]
属性用于HTTP缓存(又名响应缓存),而不是用于服务器端缓存。此属性在响应中设置响应缓存标头,它告诉浏览器缓存响应,并且下次请求相同的 URL 时不再发出另一个 HTTP 请求。您不需要中间件来使用 [ResponseCache] 属性。
相反,服务器端缓存用于在服务器上存储/缓存响应并提供来自缓存的响应。响应缓存中间件用于服务器端缓存(
AddResponseCaching()
)。
HTTP 缓存/响应缓存的文档:https://learn.microsoft.com/en-us/aspnet/core/performance/caching/response?view=aspnetcore-8.0
服务器端缓存文档:https://learn.microsoft.com/en-us/aspnet/core/performance/caching/middleware?view=aspnetcore-8.0