piotrsz
piotrsz

Reputation: 1152

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

In my ASP.NET app I use HttpWebRequest for fetching external resources which I'd like to be cached. 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 IE cache, so when I run it as normal user (in tiny cmd test app), data is cached to %userprofile%\Local Settings\Temporary Internet Files and next responses are read from cache.

I thought that when such code is run inside ASP.NET app, data will be cached to ...\ASPNET\Local Settings\Temporary Internet Files but it is not and cache is never used.

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

Upvotes: 7

Views: 3324

Answers (3)

Dan Mork
Dan Mork

Reputation: 1818

I know this is an old thread, but another thing to consider regarding this issue is the IE security settings for the user account the ASP.NET application is running as. HTTP caching (CachePolicy.Level = Default, HTTP cacheable resources) was not working for our application until we added the remote host to the Trusted Sites list.

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

Upvotes: 1

MUG4N
MUG4N

Reputation: 19717

You can use the cache manually in your code like this:

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

You can use this Method like you would use caching with in web.config.

Upvotes: 1

Sky Sanders
Sky Sanders

Reputation: 37084

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

Check the response headers and ensure that the resource is not explicitly asking to not be cached.

Upvotes: 0

Related Questions