title: How to add a cache buster to all images in an ASP.NET MVC site
body: <p>I am trying to improve the performance of a large ASP.NET MVC website and I am currently looking for a way of adding a cache busting query string to image requests in such a way that I don't have to go through all the views and CSS and change each image reference.</p>
  
  <p><strong>Desired result</strong></p>
  
  <p>To verify if the cache buster is being added I am using the Firebug extension in Firefox and what I am looking to see is something like this (screenshot taken from another website)</p>
  
  <p><img src="https://i.stack.imgur.com/Jh3VY.png" alt="enter image description here"></p>
  
  <p><strong>What I've tried</strong></p>
  
  <p>The simplest answer seemed to me to create a custom HttpModule that intercepted any image request and then appended the cache busting query string to the request URL. So I wrote the following class</p>
  
  <pre><code>public class CacheBusterImageHandler : IHttpModule
  {
      public void Init(HttpApplication context)
      {
          context.BeginRequest += this.BeginRequest;
      }
  
      public void Dispose()
      {            
      }
  
      public void BeginRequest(object sender, EventArgs e)
      {
          // This conditional check will need to be modified to capture other image types
          // but for testing purposes it is good enough
          if (HttpContext.Current.Request.Path.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
          {
              // The version number will be generated but again for testing purposes this
              // is good enough
              var pathWithCacheBuster = string.Format("{0}?v1.0.0.0", HttpContext.Current.Request.Path);
  
              HttpContext.Current.RewritePath(pathWithCacheBuster);
          }
      }
  }
  </code></pre>
  
  <p>I then registered the module in web.config like this</p>
  
  <pre><code>&lt;system.webServer&gt;
    &lt;modules runAllManagedModulesForAllRequests="true"&gt;
      &lt;add name="CacheBusterImageHandler" type="MyAssembly.CacheBusterImageHandler" preCondition="managedHandler" /&gt;
      ...
  </code></pre>
  
  <p>I then verified that the requests were getting processed by the module by using breakpoints, however when I checked in Firebug the image requests did <em>not</em> have the cache buster appended to URL. I then decided to read the documentation for the RewritePath method and found that of course it simply redirects the request but does not alter the requested URL.</p>
  
  <p><strong>Questions</strong></p>
  
  <p>Is there a way in an HttpModule to append the cache buster to the query string?</p>
  
  <p>If not, is there some other way I can achieve the same result without having to modify every reference to an image?</p>