简体   繁体   中英

How to cache image returned by HttpResponseMessage

I have a problem with caching images returned by HttpResponseMessage.

Files are accessed by urls:

http://localhost:[service port]/[file GUID]?Adapter=[adapter type]

eg:

http://localhost:59292/b9e7d18a-2eaf-11e4-92e3-8056f2d1ef7b?Adapter=CoolAdapter

I add CacheControl headers to a HttpResponseMessage:

new CacheControlHeaderValue()
                   {
                       Public = true,
                       MaxAge = TimeSpan.FromSeconds(60)
                   };

Both cache control headers of response are correctly shown in browser (Chrome) but still every refresh of that url executes method for retrieving image on server instead of serving this picture from cache.

Am I missing something (IIS config, url form)?

You want to add image to IIS cache and wonder why it is downloaded multiple times? IIS cache is useful if you have multiple clients who want the same resource.

You can check to see your current cache with (command line):

netsh http show cachestate

You most likely want browser cache - same client requests same file over and over again in short period . The following should cause the browsers to cache your images:

<staticContent>
    <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1.00:00:00" />
</staticContent>
<httpProtocol>
    <customHeaders>
        <add name="Cache-Control" value="public" />
    </customHeaders>
</httpProtocol>

I use the following code for that:

var age = new TimeSpan(cacheTime, 0, 0);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
    MaxAge = age,
    Public = false,
    NoCache = false,
    Private = true,
};
response.Content.Headers.Expires = DateTime.UtcNow.Add(age);

Not sure if the trick is the Expires part, or the fact I use 24 hours as my cache time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM