我试着在.NET Core3.1中学习响应缓存。但这不像我所希望的那样有效。我在Chrome中查看了网络,它用cache-control: no-cache, no-store显示了响应头。
我还发现响应头与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();
}发布于 2020-10-19 14:20:20
这是正常行为,如果从磁盘缓存或不从磁盘缓存检索页面,会有多个因素在发挥作用。
我将尝试列出用户请求页面的常见场景,以及页面是否缓存。
AddResponseCaching和UseResponseCaching控制服务器端缓存,而ResponseCacheAttribute通过设置适当的头来控制客户端缓存。我喜欢控制客户端缓存的方式是设置配置文件,如下所示:
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报头,这是服务器所尊重的。1. Open your Chrome dev tools and uncheck the `Disable cache` checkbox if it's checked.2. Request your page like you normally would.3. Not try to request the same page via an anchor tag in the page that reference the same page (you should see that the page is retrieved from disk cache) (if the conditions below are respected).4. Also you can navigate to your (cache activated) page from another page, if it's cached it will be pulled from the disk cache (if the conditions below are respected).Cache-Control和Pragma头一起发送到no-cache。您可以看到在MSDN上缓存的所有条件。no-cache头。https://stackoverflow.com/questions/64413717
复制相似问题