我希望在没有任何条件的情况下强制缓存HttpRequest响应。但似乎有时它不起作用。可能是看标题,但我不想要它。例如,this url有时不会缓存。这是一个代码:
public static class HttpRequestHelper
{
public const string ContentTypeForm = "application/x-www-form-urlencoded";
public static HttpWebRequest CreateRequest(Uri uri)
{
HttpWebRequest request = WebRequest.CreateHttp(uri);
request.Proxy = null;
return request;
}
public enum CacheMode
{
None = 0,
Hourly,
Max,
}
public static string Request(Uri uri, CacheMode cache = CacheMode.None)
{
HttpWebRequest request = CreateRequest(uri);
if (cache != CacheMode.None)
request.CachePolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxStale,
cache == CacheMode.Hourly ? TimeSpan.FromHours(1) : TimeSpan.FromDays(365));
return GetContent(request);
}
public static HttpWebResponse GetResponse(HttpWebRequest request)
{
Contract.Requires(request != null);
Debug.WriteLine("Request: " + request.RequestUri);
var response = request.GetResponse() as HttpWebResponse;
return response;
}
public static string GetContent(WebRequest request)
{
Contract.Requires(request != null);
string data = "";
using (var response = (HttpWebResponse)request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
if (responseStream == null) return data;
using (var reader = new StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
}
return data;
}
}
答案 0 :(得分:0)
最可能的原因是服务器的响应指定了某种“不缓存”标头。即它可能是Pragma: no-cache
- 所以尽管你付出了努力,项目也不会被缓存。
可能的解决方法是将结果自己缓存在内存中或磁盘上......