Search code examples
c#cachinghttpclient

Method to determine if caching was used for a particular HttpClient request


The new .NET 4.5 HttpClient class is handy for sending off web requests so I'm trying to use it instead of the old HttpWebRequest and related classes.

I can get it to do just about everything I used to do, including decompression, caching...

But how do I know if a completed request was satisfied by the cache or not?

This was possible before:

using (var resp = request.GetResponse())
using (var rs = resp.GetResponseStream())
{
    if (!resp.IsFromCache)
    {
        //do something
    }
}

Where can I add that check here?

HttpClient client = new HttpClient(
            new WebRequestHandler
            {
                AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
                CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable),
                UseDefaultCredentials = true,
                PreAuthenticate = true
            });
var data = await client.GetByteArrayAsync(uri);
//did that come from the cache?
return data;

Anticipating "why do you need to know if it was from the cache?" ... well I happen to want to know if I just communicated with the server, because if I did then I'll extend a session keep-alive timer... but if I just got that from the cache and didn't even go to the server, I may need to send a session keep alive request sooner... session creation for this server takes at least a couple of seconds and I want to avoid it.

If I use the more piece-meal methods on HttpClient, there is more room to investigate the response and look for status codes and headers:

var resp = await client.GetAsync(uri);
resp.EnsureSuccessStatusCode();
//can look at status codes, headers etc here
return await resp.Content.ReadAsByteArrayAsync();

The status code appears to be 200 whether it is cached or not ... there are some interesting things in the header, but I'm not sure how to interpret all of them.

For instance resp.Headers.Date looks like its the date response was cached, so if its sufficiently far in the past (more than a couple of seconds?) that might tell me if its cached or not. But I just don't know how reliable that kind of thinking is ...


Solution

  • The Age header shows that it's from the cache. On the left is the 1st (uncached) request, and on the right, the 2nd (cached) request:

    enter image description here