Created
September 14, 2014 13:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Html.GetCacheableUrl("~/css/default.css") in combination with if (url.StartsWith("/") && !url.StartsWith("//")) doesn't seem to work ;)