Last active
January 3, 2016 15:09
-
-
Save eerrecart/8480540 to your computer and use it in GitHub Desktop.
I've made this to append a query string with a "number version" according to the assets content, so it works as Cache BUST for CDN caching services (i.e: cloudfront). It only check the last modified date of each asset inside a bundle and create a token, you can create a MD5 o change to something more cool. The code is executed wen a file changes…
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
/// <summary> | |
/// uses the BuildCundleContent to create a file midification token, but we need to keep the BaseBuilder functionality, so we | |
/// take them from the ctr. | |
/// </summary> | |
public class SetAssetVersion : IBundleBuilder | |
{ | |
public IBundleBuilder BaseBuilder { get; set; } | |
public SetAssetVersion(IBundleBuilder baseBuilder) | |
{ | |
BaseBuilder = baseBuilder; | |
} | |
public string BuildBundleContent(Bundle bundle, BundleContext context, System.Collections.Generic.IEnumerable<BundleFile> files) | |
{ | |
if (bundle == null) | |
{ | |
throw new ArgumentNullException("bundle"); | |
} | |
long tokenTime = 0; | |
foreach (BundleFile file in files) | |
{ | |
if (HttpContext.Current != null) | |
{ | |
var fileInfo = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(file.VirtualFile.VirtualPath)); | |
tokenTime += fileInfo.LastWriteTimeUtc.Ticks; | |
} | |
} | |
bundle.CdnPath = bundle.CdnPath.Split(new char[] { '?' }, 2, StringSplitOptions.RemoveEmptyEntries).First() | |
+ "?v=" + tokenTime.ToString(); | |
//return the original result of the BuildBundleContent method from the BaseBuilder (Default). | |
return BaseBuilder.BuildBundleContent(bundle, context, files); | |
} | |
} |
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
public static void RegisterBundles(BundleCollection bundles) | |
{ | |
BundleTable.EnableOptimizations = true; | |
bundles.UseCdn = true; | |
StyleBundle cssBundle = new StyleBundle("~/bundles/css", | |
"http://cdn.localhost:39061/bundles/css"); | |
//using our coustom code, and keeping the base builder | |
cssBundle.Builder = new SetAssetVersion(cssBundle.Builder); | |
cssBundle.Include("~/css/Copy of miceceese.css", | |
"~/css/miceceese.css", | |
"~/css/periplo.css"); | |
bundles.Add(cssBundle); | |
//result: http://cdn.localhost:39061/bundles/css?v=6352530398450671462 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment