How do I add Cache busting with .NET Projects?

  • Page Owner: Not Set
  • Last Reviewed: 2021-05-12

How do I add cache busting to a .NET Project so that I do not need to clear cloudflare cache (DXP sites), etc.

Comments


Answer

For .Net 5 projects (Opti 12, and Umbraco 9?) You can use the asp directive in razor to auto append version.

<script src="/static/js/main.js" asp-append-version="true" type="module"></script>

Additional Posts

The easiest way to add cache busting to a project for .NET 4.8 and below is to add a Cache busting class. Below is an example from CHCO. This will generate a GUID then convert it to random characters.

using System;
using System.Text.RegularExpressions;
namespace ChildrensHospitalColorado.Business
{
    public static class ClientCache
    {
        public static readonly string CacheBuster = Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "");
    }
}

To use, simply append as a GET parameter to your resource, for example.

CSS: 
<link rel="stylesheet" href="/mycssfile.css?v=@ClientCache.CacheBuster" />

JS:
<script src="/myjsfile.js?v=@ClientCache.CacheBuster"></script>