How to get RequestCachePolicy to respect max-age

十年热恋 提交于 2019-12-10 18:20:55

问题


I am confused about how time-based cache policies work when using HttpWebRequest.

I am calling a GET method of a WebAPI that returns JSON content together with a Cache-Control header similar to:

Cache-Control: public, max-age=60

The intention is that the content should be considered to be stale after max-age seconds.

I am calling this API using HttpWebRequest, and want subsequent requests to be served from the local cache for max-age seconds, then to be retrieved from the server when the content expires.

I've tried different combinations with the results listed below.

  1. Do not specify a RequestCachePolicy. In this case, as expected, all requests go to the server.

  2. Specify a default cache policy:

    var policy = new RequestCachePolicy(RequestCacheLevel.Default);
    HttpWebRequest.DefaultCachePolicy = policy;
    

    In this case, all requests still go to the server. I was expecting requests to be served from the cache for the next max-age seconds.

  3. Specify a cache policy CacheIfAvailable:

    var policy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable);
    HttpWebRequest.DefaultCachePolicy = policy;
    

    In this case, all requests are served from the local cache, even if the content is stale (i.e. max-age seconds has passed).

Is it possible to achieve what I want, and if so, how?


回答1:


It seems that it's necessary for the server to add an Expires header to the response, in addition to (or instead of?) the Cache-Control header. The poster of that answer deserves the bounty.

When an Expires header is present, and RequestCacheLevel.Default is used, expiry behaves as expected in a .NET Framework application: the request is served from the local cache until the expiry time is reached.

However in a .NET Core application, using the same code, all requests are sent to the server and the local cache isn't used :( This is separate to the subject of my original question so I've asked a new question.



来源:https://stackoverflow.com/questions/55693462/how-to-get-requestcachepolicy-to-respect-max-age

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!