Automatic Versioning & “Cache Busting”

Implemented a CDN/caching layer but haven’t had time to get the versioning of assets worked out properly? Try some basic “cache-busting” using a querystring parameter which gets updated each time you build:

Update AssemblyInfo.cs to end with an asterisk (“*”):

[assembly: AssemblyVersion("1.0.0.*")]

Create a little helper method:

    public static class AppHelper
        private static string _version;
        public static string SiteVersion()
            return _version ?? (_version = 
                        Assembly.GetAssembly(typeof (HomeController))

And use this value in static file references:

<img src="/img/[email protected]()" alt="Logo" />

Which will render something like:

<img src="/img/logo.png?v=" alt="Logo" />

This number will change with every build, so should force retrieval of updated static – cached – content.

2 thoughts on “Automatic Versioning & “Cache Busting”

  1. Do you really want to invalidate everyone’s cached image files every time you deploy a new version of your site? Probably not. You are better off using logic to check last modified date or using a hash of content I think.

    • Sure, this is indeed an imperfect solution for an actual caching strategy. However, it allows us to easily ensure static resources with long expires, in a CDN perhaps, are actually picked up.

      You also need to balance the impact of forcing retrieval of your chosen static files each deployment vs end users getting stale versions.

      I’m using this as a stop gap solution until I get around to implementing a more intelligent cache strategy.

      Good comment, thanks. Do you have a preferred implementation of such logic?

Leave a Reply to Pablo Jimenez Cancel reply

Your email address will not be published. Required fields are marked *