Skip to content

Instantly share code, notes, and snippets.

@abjerner
Created September 14, 2014 13:01
Show Gist options
  • Save abjerner/65979ea01cf3980ca908 to your computer and use it in GitHub Desktop.
Save abjerner/65979ea01cf3980ca908 to your computer and use it in GitHub Desktop.
A set of extension methods to help with fingerprinting (cache busting) of static resources in ASP.NET MVC views. In your view, just call @Html.GetCacheableUrl("~/css/default.css") and the timestamp will be appended to the query string.
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Skybrud.Umbraco.ExtensionMethods {
public static class HtmlHelperExtensionMethods {
public static string GetCacheableUrl(this HtmlHelper helper, string url) {
return GetCacheableUrl(url);
}
public static string GetCacheableUrl<T>(this HtmlHelper<T> helper, string url) {
return GetCacheableUrl(url);
}
public static string GetCacheableUrl(string url) {
if (String.IsNullOrWhiteSpace(url)) return "";
if (url.StartsWith("/") && !url.StartsWith("//")) {
FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath("~" + url));
if (file.Exists) {
long ticks = file.LastWriteTimeUtc.Ticks;
return url + (url.Contains("?") ? "&" : "?") + ticks;
}
return url;
}
return url;
}
}
}
@Bernoulli-IT
Copy link

@Html.GetCacheableUrl("~/css/default.css") in combination with if (url.StartsWith("/") && !url.StartsWith("//")) doesn't seem to work ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment