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.
Do not specify a RequestCachePolicy
. In this case, as expected, all requests go to the server.
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.
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?
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.