views:

1781

answers:

2

I am developing against a proprietary library and are experiencing some issues with the cache of the HttpWebRequest. The library is using code equivalent to below to make requests:

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

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

The external resource doesn't disallow caching although each response differs. Thus I am ending up getting the same response each time.

Is there any way to clear the contents of the HttpWebRequest cache? The right solution would be to fix the external source or perhaps change the cache policy, but neither is possible - hence the question.

Clearing the cache could have various impacts, so preferably the solution would be to invalidate the cache on a per resource basis.

A: 
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;
}

You can set the Cache Policy to the request to NoCacheNoStore to the HttpWebRequest.

CyberMing
As stated it isn't possible to change the cache policy. I would like a solution for actually clearing the cache store - not avoiding caching entirely.
troethom
A: 

You can change the cache policy: use an http reverse proxy, and remove/change the relevant http headers. It's a hack, but it would work, and quite easily. I'd suggest you use Apache httpd server for this task (with mod_proxy).

Ron Klein