force browsers to get latest js and css files in asp.net application force browsers to get latest js and css files in asp.net application javascript javascript

force browsers to get latest js and css files in asp.net application


I solved this by tacking a last modified timestamp as a query parameter to the scripts.

I did this with an extension method, and using it in my CSHTML files. Note: this implementation caches the timestamp for 1 minute so we don't thrash the disk quite so much.

Here is the extension method:

public static class JavascriptExtension {    public static MvcHtmlString IncludeVersionedJs(this HtmlHelper helper, string filename) {        string version = GetVersion(helper, filename);        return MvcHtmlString.Create("<script type='text/javascript' src='" + filename + version + "'></script>");    }    private static string GetVersion(this HtmlHelper helper, string filename)    {        var context = helper.ViewContext.RequestContext.HttpContext;        if (context.Cache[filename] == null)        {            var physicalPath = context.Server.MapPath(filename);            var version = $"?v={new System.IO.FileInfo(physicalPath).LastWriteTime.ToString("MMddHHmmss")}";            context.Cache.Add(filename, version, null,              DateTime.Now.AddMinutes(5), TimeSpan.Zero,              CacheItemPriority.Normal, null);            return version;        }        else        {            return context.Cache[filename] as string;        }    }}

And then in the CSHTML page:

 @Html.IncludeVersionedJs("/MyJavascriptFile.js")

In the rendered HTML, this appears as:

 <script type='text/javascript' src='/MyJavascriptFile.js?20111129120000'></script>


In ASP.NET Core (MVC 6) this works out of the box via the asp-append-version tag helper:

<script src="scripts/myjavascript.js" asp-append-version="true"></script><link href="styles/mystyle.css rel="stylesheet" asp-append-version="true" />


Your solution works. It is quite popular in fact.

Even Stack Overflow uses a similar method:

<link rel="stylesheet" href="http://sstatic.net/so/all.css?v=6184"> 

Where v=6184 is probably the SVN revision number.