【发布时间】:2021-02-01 10:12:45
【问题描述】:
我尝试了解 .NET Core 3.1 中的响应缓存。但它并没有如我所愿。我在 Chrome devtool 中查看了网络,它显示了带有 cache-control: no-cache, no-store 的响应标头。
我还发现 Response 标头在 Actionfilter 中带有 HeaderCacheControl{public,max-age=100}。这是我预期的值,但浏览器中的实际响应头是no-cache。
Startup类:
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching(options=>
{
options.SizeLimit = 1024;
options.MaximumBodySize = 1024 * 1024 * 100;
options.UseCaseSensitivePaths = false;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCookiePolicy();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseResponseCaching();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
控制器:
[ResponseCache(Duration = 100, NoStore = false)]
public IActionResult Index()
{
return View();
}
【问题讨论】:
-
你的管道顺序不对,你在
UseEndpoints之前没有使用ResponseCaching中间件。并且提供静态文件和路由必须发生在身份验证和授权之前。 -
谢谢。我听从了您的建议并修复了中间件的顺序。还在文档中找到了信息(docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/…)。但是,修复后我仍然得到“无缓存,无存储”。
标签: c# .net caching .net-core browser