asp.net-core - ResponseCache 属性不在客户端缓存数据

标签 asp.net-core asp.net-core-mvc asp.net-core-1.0 coreclr

在 ASP.NET Core 应用程序中,我有一个返回一些数据的操作方法。我想在客户端缓存这些数据。所以基于documentation here我可以在操作方法上使用 ResponseCache 属性。此属性在响应中添加 Cache-Control header

Response caching refers to specifying cache-related headers on HTTP responses made by ASP.NET Core MVC actions. These headers specify how you want client and intermediate (proxy) machines to cache responses to certain requests (if at all). This can reduce the number of requests a client or proxy makes to the web server, since future requests for the same action may be served from the client or proxy’s cache.

还有

Response caching does not cache responses on the web server. It differs from output caching, which would cache responses in memory on the server in earlier versions of ASP.NET and ASP.NET MVC.

这就是我的操作方法的样子

public class LookupController : Controller
{
    [HttpGet]
    [ResponseCache(Duration = 120)]
    public IEnumerable<StateProvinceLookupModel> GetStateProvinces()
    {
        return _domain.GetStateProvinces();
    }
}

然后我使用浏览器调用该方法 http://localhost:40004/lookup/getstateprovinces 这是请求和响应 header

enter image description here

请注意,响应 header 具有预期的 Cache-Control: public,max-age-120。 但是,如果使用 F5 刷新页面(120 秒之前),则 GetStateProvince 操作方法内的调试器断点始终会命中。这意味着它不会在客户端缓存数据。

我还需要做些什么来启用客户端缓存吗?

更新 我尝试过使用 IE、Chrome 和 POSTMAN,但没有成功。每次我在地址栏中输入网址或点击刷新时,客户端(即浏览器或 postman )都会调用操作方法。

最佳答案

实际上,ResponseCache 属性按预期工作。
不同之处在于,如果您浏览网站页面(情况 1)或使用后退和前进按钮(不在刷新页面时),响应就会被缓存。

作为情况 1 的示例,我有以下内容:

正如您将在文章 Response Caching in ASP.Net Core 1.1 中看到的那样,声明如下:

During a browser session, browsing multiple pages within the website or using back and forward button to visit the pages, content will be served from the local browser cache (if not expired).
But when page is refreshed via F5, the request will be go to the server and page content will get refreshed. You can verify it via refreshing contact page using F5.
So when you hit F5, response caching expiration value has no role to play to serve the content. You should see 200 response for contact request.

引用文献:
[1]。 ASP.NET Core Response Caching Sample
[2]。 ResponseCache attribute sample
[3]:How to control web page caching, across all browsers?

关于asp.net-core - ResponseCache 属性不在客户端缓存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40369112/

相关文章:

c# - 将用户名添加到 Serilog

javascript - Blazor WebAssembly 为特定环境加载不同的脚本

c# - Identityserver4/OpenId Connect,混合模式, token 刷新失败

asp.net-core-mvc - 在 asp .net CORE/MVC 6 应用程序中设置 Swagger 时出现 500 错误

asp.net-core - VS 2015 使用 Kestrel 吗?

asp.net-core - .net core 中的打印支持

asp.net-core - 如何为 View 设置回退资源文件

C# 解决方案布局 - WPF + ASP.NET Core + 共享代码

asp.net-core-mvc - ASP NET Core 2.0 appsettings.Development.json 不适用于日志记录配置

.net - 表单提交导致 "InvalidDataException: Form value count limit 1024 exceeded."