Skip to content

Instantly share code, notes, and snippets.

@fjeldstad
Created February 3, 2012 13:56
Show Gist options
  • Save fjeldstad/1730281 to your computer and use it in GitHub Desktop.
Save fjeldstad/1730281 to your computer and use it in GitHub Desktop.
Simple UrlHelper extension for rendering app-relative content urls with last-modified timestamp appended as a querystring parameter.
using System;
using System.IO;
using System.Web.Mvc;
using System.Web;
namespace Example.Web.Helpers
{
public static class UrlHelperExtensions
{
/// <summary>
/// Like Url.Content(...) but also appends a timestamp representing the last write date and time
/// of the file to the querystring. Useful for cache-busting.
/// </summary>
/// <param name="helper"></param>
/// <param name="contentPath"></param>
/// <returns></returns>
public static string ContentWithTimestamp(this UrlHelper helper, string contentPath)
{
var contentUrl = helper.Content(contentPath);
try
{
var fileLastModifiedTicks = File.GetLastWriteTime(HttpContext.Current.Server.MapPath(contentPath)).Ticks;
return contentUrl.Contains("?") ? contentUrl + "&" + fileLastModifiedTicks : contentUrl + "?" + fileLastModifiedTicks;
}
catch (Exception ex)
{
return contentUrl;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment