In this article I'll demonstrate a very simple way to cache bust your static CSS, JS and image files in ASP.NET Core.
Like the good developer you are, you have most likely added the cache-control header for your static CSS, JS and image files. With the cache-control in place it's telling the browser to cache these files for a specified amount of time. Which is great as the browser will now use the cached file version and not request the file direct from your server. This is all groovy, until the time comes when you update these files and deploy a new version of them. You will still see the old version until the cache has expired.
The good news is this can be fixed by appending a query string variable with a different value to the end of the file, like so:
/dist/css/style.css?v=9808c17d-9ca6-4d2d-a708-884f6dd510b5
With a different value for the query string, the browser will recognise this as a new file and therefore request and re-cache the new file.
There are lots of different ways to generate this version number programatically, however in ASP.NET Core they have already thought about this. Simply by appending the attribute asp-append-version="true" to your CSS, JS and image HTML tag. ASP.NET Core will recognise the file has changed and automatically generate a new version number for you.
This in your razor file:
<link rel="stylesheet" href="/dist/css/style.css" asp-append-version="true"> <script src="~/dist/js/main.js" asp-append-version="true"></script>
Becomes this when you view the page source:
<link rel="stylesheet" href="/dist/css/style.css?v=YR4kXP93_AgVno-gXKI0l3oxl-I_KMkSGbaDHAc2E0M"> <script src="/dist/js/main.js?v=bsJHJ1dBuKGZth_fZXgiTt76SmS6QznXmwuJUyWkXqA"></script>