我试图了解 .NET Core 3.1 中的响应缓存。但它没有如我所愿。我在 Chrome devtool 中查看了网络,它显示了带有 cache-control: no-cache, no-store
的响应头.
我还发现响应头是 HeaderCacheControl{public,max-age=100}
在 Action 过滤器中。这是我期望的值,但浏览器中的实际响应头是 no-cache
.Startup
类(class):
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?}");
});
}
Controller :[ResponseCache(Duration = 100, NoStore = false)]
public IActionResult Index()
{
return View();
}
最佳答案
这是正常行为,如果页面是否从磁盘缓存中检索,则有多种因素会起作用。
我将尝试列出用户请求页面以及它是否被缓存的常见场景。
AddResponseCaching
和 UseResponseCaching
控制服务器端缓存 ResponseCacheAttribute
通过设置适当的 header 来控制客户端缓存。 我喜欢控制客户端缓存的方式是通过设置如下配置文件:
services.AddControllersWithViews(options =>
{
options.CacheProfiles.Add("Caching", new CacheProfile()
{
Duration = 120,
Location = ResponseCacheLocation.Any,
VaryByHeader = "cookie"
});
options.CacheProfiles.Add("NoCaching", new CacheProfile()
{
NoStore = true,
Location = ResponseCacheLocation.None
});
})
你像这样使用它:[ResponseCache(CacheProfileName = "Caching")]
Cache-Control: no-cache
Cache-Control: max-age=0
带有服务器尊重的请求的 header 。Disable cache
复选框如果它被选中。Cache-Control
一起发送和 Pragma
标题到 no-cache
.您可以在 MSDN 上看到缓存的所有条件。 .no-cache
默认标题。关于c# - ResponseCache 在网络核心 3.1 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64413717/