skttl
10/21/2016 - 7:26 AM

Adds the last write time of a file, to a querystring parameter, for busting local caches. Usage: @UrlHelpers.CachebustPath("~/path/to/style

Adds the last write time of a file, to a querystring parameter, for busting local caches.

Usage: @UrlHelpers.CachebustPath("~/path/to/styles.css")

using Umbraco.Core;

namespace MyWebsite.Core.Helpers
{

    public static class UrlHelpers
    {
        /// <summary>
        /// Takes a path, and adds a querystring value matching the last write time, to bust eventual browser caching.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string CachebustPath(string path)
        {
            var file = System.Web.HttpContext.Current.Server.MapPath(path);
            if (System.IO.File.Exists(file))
            {
                return path + "?" + System.IO.File.GetLastWriteTime(file).Ticks.ToString().ToUrlSegment();
            }
            else
            {
                return path + "?404";
            }
        }
    }
}