如何获得RequestCachePolicy以尊重最大寿命 [英] How to get RequestCachePolicy to respect max-age
问题描述
我对基于时间的缓存策略在使用 HttpWebRequest
时有效。
我正在调用a的GET方法WebAPI返回JSON内容以及类似于以下内容的Cache-Control标头:
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
目的是认为在 max-之后,内容应视为过时年龄
秒。
我正在使用 HttpWebRequest
调用此API,并且需要后续请求从本地缓存中获取 max-age
秒,然后在内容过期时从服务器中检索。
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.
-
请勿指定
RequestCachePolicy
。在这种情况下,如预期的那样,所有请求都会发送到服务器。
Do not specify a
RequestCachePolicy
. In this case, as expected, all requests go to the server.
指定默认缓存策略:
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.
指定缓存策略 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?
推荐答案
服务器似乎有必要除了(或代替?)Cache-Control标头之外,还向响应添加一个Expires标头。
当存在Expires标头并使用RequestCacheLevel.Default时,到期在.NET Framework应用程序中的行为符合预期:
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.
但是,在.NET Core应用程序中,使用相同的代码,所有请求都将发送到服务器,并且不使用本地缓存:(这与我原来的问题无关,所以我提出了一个新问题。
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.
这篇关于如何获得RequestCachePolicy以尊重最大寿命的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!