Create File Version using IFileVersionProvider in ASP.NET Core Razor
Context
In ASP.NET Core MVC Razor Pages, we can use tag helpers to create versioned file (static resources) URLs. This version is linked to file content, usually created via hash of the file content. The version can be very useful if you want to cache static resources in client but force them to refresh when a new version of the content is published. Hence it is broadly used in ASP.NET Core applications.
For instance, the following code snippet use tag helper to append versions to URL:
<script src="~/js/site.min.js" asp-append-version="true"></script>
Once rendered, the HTML tag looks like the following:
<script src="/js/site.min.js?v=mq5mnzrvhxTo-t8D395cnkGjvAejGT3fdASXzvp5EtU"></script>
The current site.min.js
file gets a version mq5mnzrvhxTo-t8D395cnkGjvAejGT3fdASXzvp5EtU
. When the file content changes, the version value will also change.
Create version dynamically
In some circumstances, it might be useful to create the versioned URL dynamically. For example, you may want to use the URL directly in an AJAX call or in a fetch
API.
This can be achieved via interface 'Microsoft.AspNetCore.Mvc.ViewFeatures.IFileVersionProvider
'. For ASP.NET Core MVC projects, this provider is added into services automatically and can be resolved in Razor page models.
The following code shows you how to generate a version URL.
@using Microsoft.AspNetCore.Mvc.ViewFeatures; @inject IFileVersionProvider fileVersionProvider; @{ var versionedScriptPath = fileVersionProvider.AddFileVersionToPath(HttpContext.Request.PathBase, "/js/site.min.js"); }
You can then directly use the version script path in client script or HTML document (via @versionedScriptPath
).
The value of this variable is the same as the previous one:
/js/site.min.js?v=mq5mnzrvhxTo-t8D395cnkGjvAejGT3fdASXzvp5EtU