Search code examples
.nethttphttpwebrequesthttp-caching

Why aren't my HTTP caching headers working?


I recently added some HTTP caching headers to some of my web service's responses, but they so far haven't done anything for me on the client side. Here's one of these responses:

HTTP/1.1 200 OK
Cache-Control: public, max-age=60
Transfer-Encoding: chunked
Content-Type: application/vnd.com...
Expires: Thu, 27 Sep 2012 03:40:27 GMT
Server: Microsoft-IIS/7.5
Set-Cookie: DDRSSID=...
X-DDVS-Version: 1.0.0.0
X-Powered-By: ASP.NET
Date: Thu, 27 Sep 2012 03:40:22 GMT

According to both Fiddler and REDbot, this response should be entirely cacheable. Here's what Fiddler says:

public: This response MAY be cached by any cache.
max-age: This resource will expire in 1 minutes. [60 sec]

Even so, the responses are not coming from cache: I see them in Fiddler and the IsFromCache property on my HttpWebResponse is false. Here's the content of my request, fwiw:

GET http://floater/rest/folders/folder.20 HTTP/1.1
Accept: application/vnd.com....
Authorization: Basic blahblah
Host: floater

What am I missing?


Solution

  • It turns out that there wasn't anything wrong with my headers. Rather, the problem was that the default caching policy for HttpWebRequest is not HttpRequestCacheLevel.Default. My bad, I guess.

    By adding the following line to my request initialization I was able to see the caching results I expected:

    webRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
    

    Another problem I had while testing this in various respects was that responses are not cached unless you read the entire response (eg. by reading to the end of GetResponseStream()). This is thankfully noted in the documentation:

    A copy of a resource is only added to the cache if the response stream for the resource is retrieved and read to the end of the stream.