在我的应用程序中,我构建了一个GET请求,只要内容与服务器上的内容相同,就会从缓存中返回响应。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ReadWriteTimeout = 2000;
request.KeepAlive = true;
request.AutomaticDecompression = DecompressionMethods.GZip;
request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate);
request.Host = host;
request.Referer = referer;
request.UserAgent = ua;
request.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
request.ContentType = "application/json; charset=UTF-8";
request.Headers.Add("Accept-Ranges", "bytes");
request.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,en-US;q=0.5,en;q=0.3");
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (var stream = new StreamReader(response.GetResponseStream()))
{
content = stream.ReadToEnd();
}
}
else content = string.Empty;
}
但是request.GetResponse().IsFromCache
总是返回false,即使内容相同(我仍然可以使用StreamReader
成功读取它)。
当我在浏览器中连续执行相同的两个请求时,它会成功缓存。
我已经尝试了所有可能的缓存策略。谁能解释我做错了什么?