April 4, 2014

In a web page, a lot of content and different types of files are transferred from the server to the client - for example, dynamic content from asp.net / mvc, and static content like images, css and javascripts. All these types of files add to performance hit. To avoid some of these problems we can cache the static content to the client browser. So, in this post, I will talk about how to add expire header to the static files.

Asp.net already has an option to add static content by adding a staticContent element and clientCache sub-element within the system.webServer section of the web.config file. So, what this does is adds the expiration related headers appropriately. This is how the web.config file will look like.

web.config
  1. <system.webServer>
  2.   <staticContent>
  3.     <!--expire on 31st Dec 2014-->
  4.     <clientCache cacheControlMode="UseExpires" httpExpires="Wed, 31 Dec 2014 00:00:00 GMT" />
  5.     
  6.     <!--expire after 60 days-->
  7.     <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="60.00:00:00"/>
  8.   </staticContent>
  9. </system.webServer>

Above, is an example of two ways to enable caching of static content - one by specifying a hard coded date and another by a length of time.

So, now we know how to cache static content but you must be wondering how does IIS decide what files are static. Yep, this is the same one I was thinking for sometime till I figure out that there is a list of file handlers within the web.config file at C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config that determines which handler is called for which file type. If a file is not specified within this handler settings, the last option "*" kicks in IIS considers the file as a static file. File extensions like css, js, png are not listed in this file are therefore treated as a static file.

Ok, now we figured out which files will be cached and how set enable cache but what id we want to change the file. Well, I don't think we usually have an image with the same name so images are not of an issue. However, css and javascript are. To avoid the caching problem for css and javascript files, we should specify a new file name whenever the file is modified. Now, there is a problem with this approach if you bundling and minification. It means the application will need to be re-compiled and re-deployed for the changes in javascript or css to take effect.

0 comments:

Reference: Shahed Kazi at AspNetify.com