Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Asp.net/iis to set Cache-control:max-age for static files

Tags:

We have a Webforms project with url routing. I have defined exception routes for images and css-files as

routes.Add("IgnoreImages", new Route("img/{*pathInfo}", new StopRoutingHandler()));
routes.Add("IgnoreCss", new Route("css/{*pathInfo}", new StopRoutingHandler()));

so static files should be served by IIS directly and routing should be bypassed.

When checking the response for an image with Fiddler the only key under the Cache heading is Date. What's missing is the Cache-control:max:age key. How can I specify caching policy for static files? The application is run on IIS7.5.

like image 772
Mathias Rönnlund Avatar asked Jun 06 '11 11:06

Mathias Rönnlund


People also ask

How can set cache control no store in asp net?

The first line sets Cache-control to no-cache , and the second line adds the other attributes no-store, must-revalidate . This may not be the only way, but does provide an alternative method if the more straightforward Response. AppendHeader("Cache-control", "no-cache, no-store, must-revalidate"); fails.

What is clientCache?

Overview. The <clientCache> element of the <staticContent> element specifies cache-related HTTP headers that IIS 7 and later sends to Web clients, which control how Web clients and proxy servers will cache the content that IIS 7 and later returns.


2 Answers

Dario's answer got me most of the way but I had to add an attribute to <clientCache>, cacheControlCustom="public", otherwise IIS did not send the Cache-Control header to the browser. See this answer.

like image 37
Evan Haas Avatar answered Oct 14 '22 21:10

Evan Haas


The solution is using the system.webserver section in the web.config file to configure server caching (and compression). Here is a starting point: http://www.iis.net/ConfigReference/system.webServer/staticContent/clientCache

Example:

<configuration>
  <system.webServer>
    <staticContent>
       <clientCache cacheControlMode="UseMaxAge"
        cacheControlMaxAge="1.00:00:00" /> <!-- 1 day -->
    </staticContent>
  </system.webServer>
</configuration>
like image 134
Dario Solera Avatar answered Oct 14 '22 19:10

Dario Solera