Automatically Breaking Js and Css Cache Using Build Number in Asp.Net

So you implement a sweet new section to your website and publish. You tell all your friends and family how amazing this new section of your pets blog is. They report back to you that it looks terrible and ugly but it was a good effort. After the back and forth of making sure they aren’t on Netscape 4 or IE 6 you realize that they have to refresh their cache. Bah!

The method that I use to avoid this problem is auto-incrementing css and javascript versions based on the build number of the application. How do you set that up? Well first open your AssemblyInfo.cs and change out some lines:

[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]

Then you can create a quick extension to pull the build number out of the assembly for popping the cache:

public static string BuildNumber(this HtmlHelper html)
{
    if (html.ViewContext.HttpContext.Cache["_buildnumber_"] == null)
    {
        var version = System.Reflection.Assembly
            .GetExecutingAssembly().GetName().Version;
        html.ViewContext.HttpContext.Cache["_buildnumber_"] =
            version.Build.ToString();
    }
    return html.ViewContext.HttpContext.Cache["_buildnumber_"].ToString();
}

Now use it in any razor file:

<script
  type="text/javascript"
  src="/js/[email protected]()"
></script>

Hope this helps.