Skip to content

Instantly share code, notes, and snippets.

@bh3605
Created January 28, 2022 02:23
Show Gist options
  • Save bh3605/820690cdba784bda2f7e6efae93903eb to your computer and use it in GitHub Desktop.
Save bh3605/820690cdba784bda2f7e6efae93903eb to your computer and use it in GitHub Desktop.
Webforms Cache Buster
sing System.Collections.Concurrent;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;
/**
* Solution from https://stefanolsen.com/posts/cache-busting-with-asp-net-mvc/
* https://www.madskristensen.net/blog/cache-busting-in-aspnet/
* https://stefanolsen.com/posts/cache-busting-2-0-an-update-for-asp-net-core/
*/
public static class Fingerprint
{
private static readonly ConcurrentDictionary<string, string> CachedFileHashes = new ConcurrentDictionary<string, string>();
public static string Version(string contentPath)
{
var physicalPath = HttpContext.Current.Server.MapPath(key);
// Check if we already cached the file hash in the cache. If not, add it using the inner method.
string fileHash = CachedFileHashes.GetOrAdd(physicalPath, key =>
{
var fileInfo = new FileInfo(key);
// If file exists, generate a hash of it, otherwise return null.
return fileInfo.Exists ? ComputeFileHash(fileInfo.OpenRead()) : null;
});
return $"{contentPath}?v={fileHash}";
}
private static string ComputeFileHash(Stream fileStream)
{
using(SHA256 hasher = new SHA256Managed())
using(fileStream)
{
byte[] hashBytes = hasher.ComputeHash(fileStream);
var sb = new StringBuilder(hashBytes.Length * 2);
foreach(byte hashByte in hashBytes)
{
sb.AppendFormat("{0:x2}", hashByte);
}
return sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment