How to force HttpWebRequest to use cache in ASP.NET?

In my ASP.NET application, I use HttpWebRequest to retrieve external resources that I would like to cache. Consider the following code:

var req = WebRequest.Create("http://google.com/"); req.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable); var resp = req.GetResponse(); Console.WriteLine(resp.IsFromCache); var answ = (new StreamReader(resp.GetResponseStream())).ReadToEnd(); Console.WriteLine(answ.Length); 

HttpWebRequest uses the IE cache, so when I run it as a regular user (in a tiny cmd test application), the data is cached to %userprofile%\Local Settings\Temporary Internet Files , and the following responses are read from the cache.

I thought that when such code runs inside an ASP.NET application, the data will be cached until ...\ASPNET\Local Settings\Temporary Internet Files , but this is not the case and the cache is never used.

What am I doing wrong? How to force HttpWebRequest to use cache in ASP.NET?

+7
source share
3 answers

You can use the cache manually in your code as follows:

  Cache.Insert("request", req, Nothing, DateTime.Now, TimeSpan.FromSeconds(30), TimeSpan.Zero) 

You can use this method as if you used caching in web.config.

+1
source

I know this is an old thread, but another thing to keep in mind with this issue is the IE security settings for the user account in which the ASP.NET application is running. HTTP caching (CachePolicy.Level = Default, HTTP cacheable resources) did not work for our application until we added the remote host to the list of trusted sites.

This article was useful for troubleshooting cache issues: http://blogs.msdn.com/b/ieinternals/archive/2011/03/19/wininet-temporary-internet-files-cache-and-explorer-folder-view. aspx

+1
source

I could be wrong, but I suspect that HttpWebRequest respects the cache headers from the resource, regardless of your stated wishes.

Check the response headers and make sure that the resource is not explicitly requesting caching.

0
source

All Articles