我正在尝试在我的.NET客户端和服务器之间使用缓存。在WinInet决定缓存结果之前,我看到了一些看似随机的端点命中次数。
.NET客户端使用HttpWebRequest
进行请求:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uiTextBoxUrl.Text);
var policy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable);
webRequest.CachePolicy = policy;
WebResponse webResponse = webRequest.GetResponse();
服务器使用ASP.net Web API实现,设置这些CacheControl
头:
response.Headers.CacheControl = new CacheControlHeaderValue
{
MaxAge =3600,
MustRevalidate = true,
Public = true,
Private = true
};
使用具有发送请求到端点的按钮的测试工具,即使使用了“CacheIfAvailable”,我仍然可以看到响应未立即缓存。通过检查服务器上的调试输出,我发现需要似乎随机数量的点击(或更可能是命中计数/经过时间启发式),才能最终缓存请求。如果我快速点击测试按钮,它将在约10次点击后开始缓存。如果我每1或2秒钟点击一次按钮,我已经数过25次点击,然后缓存才会启动。
这是我从Fiddler看到的响应:
HTTP/200 responses are cacheable by default, unless Expires, Pragma, or Cache-Control headers are present and forbid caching.
HTTP/1.1 Cache-Control Header is present: public, must-revalidate, max-age=3600, private
private: This response MUST NOT be cached by a shared cache.
public: This response MAY be cached by any cache.
max-age: This resource will expire in 1 hours. [3600 sec]
must-revalidate: After expiration, the server MUST be contacted to verify the freshness of this resource.
HTTP/1.1 ETAG Header is present: "3488770a-8659-4fc0-b579-dcda9200a1c7"
我读到HttpWebRequest
使用WinInet进行缓存,因此我很好奇WinInet如何确定需要缓存的内容,更具体地说,为什么它在第一次请求时不进行缓存?