Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@stefanolsen
Created April 20, 2019 09:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stefanolsen/8d1bfea4dd4f1ec2ef9ec84c3dd8e878 to your computer and use it in GitHub Desktop.
Save stefanolsen/8d1bfea4dd4f1ec2ef9ec84c3dd8e878 to your computer and use it in GitHub Desktop.
Code listings for blog post about cache busting and long time caching. Read about it here: https://stefanolsen.com/posts/cache-busting-2-an-update-for-aspnet-core/
using Microsoft.AspNetCore.Builder;
using Microsoft.Net.Http.Headers;
public class Startup
{
public void Configure(IApplicationBuilder app)
{
var staticFileOptions = new StaticFileOptions
{
OnPrepareResponse = context =>
{
const int secondsInAYear = 365 * 24 * 60 * 60;
context.Context.Response.Headers[HeaderNames.CacheControl] = $"public,maxAge={secondsInAYear}";
}
};
app.UseStaticFiles(staticFileOptions);
}
}
public static class UrlHelperExtensions
{
private const string WebRootBasePath = "wwwroot";
private static readonly ConcurrentDictionary<string, string> CachedFileHashes =
new ConcurrentDictionary<string, string>();
public static string ContentVersioned(this IUrlHelper urlHelper, string contentPath)
{
string url = urlHelper.Content(contentPath);
// Check if we already cached the file hash in the cache. If not, add it using the inner method.
string fileHash = CachedFileHashes.GetOrAdd(url, key =>
{
var fileInfo = new FileInfo(WebRootBasePath + key);
// If file exists, generate a hash of it, otherwise return null.
return fileInfo.Exists
? ComputeFileHash(fileInfo.OpenRead())
: null;
});
return $"{url}?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