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

Mathias Rönnlund picture Mathias Rönnlund · Jun 6, 2011 · Viewed 21.3k times · Source

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.

Answer

Dario Solera picture Dario Solera · Jun 6, 2011

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>