如何清除HttpWebRequest的缓存

时间:2009-02-10 13:00:25

标签: .net caching httpwebrequest

我正在针对专有库进行开发,我遇到了HttpWebRequest缓存的一些问题。该库使用与下面相同的代码来发出请求:

var request = WebRequest.Create("http://example.com/") as HttpWebRequest;

request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);

尽管每个响应都不同,但外部资源不会禁止缓存。因此,我每次都得到相同的答案。

有没有办法清除HttpWebRequest缓存的内容?正确的解决方案是修复外部源或者更改缓存策略,但两者都不可能 - 因此问题。

清除缓存可能会产生各种影响,因此最好解决方案是在每个资源的基础上使缓存无效。

5 个答案:

答案 0 :(得分:14)

public static WebResponse GetResponseNoCache(Uri uri)
{
        // Set a default policy level for the "http:" and "https" schemes.
        HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
        HttpWebRequest.DefaultCachePolicy = policy;
        // Create the request.
        WebRequest request = WebRequest.Create(uri);
        // Define a cache policy for this request only. 
        HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
        request.CachePolicy = noCachePolicy;
        WebResponse response = request.GetResponse();
        Console.WriteLine("IsFromCache? {0}", response.IsFromCache);            
        return response;
}

您可以将缓存策略设置为对NoCacheNoStore的请求到HttpWebRequest。

答案 1 :(得分:10)

HttpWebRequest使用System.Net.Cache.RequestCache进行缓存。这是一个抽象的类; Microsoft CLR中的实际实现是Microsoft.Win32.WinInetCache,顾名思义,它使用WinInet函数进行缓存。

这与Internet Explorer使用的缓存相同,因此您可以使用IE的“删除浏览历史记录”对话框手动清除缓存。 (首先将其作为测试,以确保清除WinInet缓存可以解决您的问题。)

假设清除WinInet缓存可以解决问题,您可以通过P /调用DeleteUrlCacheEntry WinInet API以编程方式删除文件:

public static class NativeMethods
{
    [DllImport("WinInet.dll", PreserveSig = true, SetLastError = true)]
    public static extern void DeleteUrlCacheEntry(string url);
}

答案 2 :(得分:1)

我还没有尝试,但解决方案可能是将任意查询字符串添加到所请求的网址。

这个查询字符串每次都会改变,也许使用DateTime.Now意味着每次都会有不同的url。然后,每个请求都会被重新请求。

答案 3 :(得分:0)

您可以更改缓存策略:使用http反向代理,并删除/更改相关的http标头。这是一个黑客,但它会工作,而且很容易。我建议您使用Apache httpd服务器执行此任务(使用mod_proxy)。

答案 4 :(得分:-1)

添加以下行以在Webclient获取数据时清除缓存:

Webclient.Headers.Add(HttpRequestHeader.CacheControl, "no-cache")
相关问题