Skip to content

Commit

Permalink
Force browsers to check for modifications to Blazor-served resources.…
Browse files Browse the repository at this point in the history
… Fixes #371
  • Loading branch information
SteveSandersonMS committed Apr 6, 2018
1 parent c8575af commit 1aca8d3
Showing 1 changed file with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
using Microsoft.AspNetCore.Blazor.Server;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using System.IO;
using System.Net.Mime;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Net.Http.Headers;
using System.Net.Mime;

namespace Microsoft.AspNetCore.Builder
{
Expand Down Expand Up @@ -46,6 +46,7 @@ public static void UseBlazor(
{
FileProvider = new PhysicalFileProvider(config.DistPath),
ContentTypeProvider = CreateContentTypeProvider(),
OnPrepareResponse = SetCacheHeaders
};

// First, match the request against files in the client app dist directory
Expand All @@ -60,7 +61,8 @@ public static void UseBlazor(
// to null so that it only serves files that were copied to dist
applicationBuilder.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(config.WebRootPath)
FileProvider = new PhysicalFileProvider(config.WebRootPath),
OnPrepareResponse = SetCacheHeaders
});
}

Expand All @@ -75,6 +77,24 @@ public static void UseBlazor(
});
}

private static void SetCacheHeaders(StaticFileResponseContext ctx)
{
// By setting "Cache-Control: no-cache", we're allowing the browser to store
// a cached copy of the response, but telling it that it must check with the
// server for modifications (based on Etag) before using that cached copy.
// Longer term, we should generate URLs based on content hashes (at least
// for published apps) so that the browser doesn't need to make any requests
// for unchanged files.
var headers = ctx.Context.Response.GetTypedHeaders();
if (headers.CacheControl == null)
{
headers.CacheControl = new CacheControlHeaderValue
{
NoCache = true
};
}
}

private static bool IsNotFrameworkDir(HttpContext context)
=> !context.Request.Path.StartsWithSegments("/_framework");

Expand Down

0 comments on commit 1aca8d3

Please sign in to comment.