I am trying to enable static file caching but seems like no effect, at least in browser i could not find response header with name cache-control
This is my code
app.UseSpaStaticFiles(new StaticFileOptions
{
RequestPath = _settings.SpaRoute,
});
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
// Cache static files for 30 days
ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=2592000");
ctx.Context.Response.Headers.Append("Expires", DateTime.UtcNow.AddDays(30).ToString("R", CultureInfo.InvariantCulture));
}
});
After building and running my app in local env i got the following response headers
As you can see no cache control header represented here, what am i doing wrong?
StaticFileMiddleware
is a terminal middleware, i.e. it short-circuits the request and never calls the next middleware in chain if it comes across a static file request that doesn't match an endpoint (among other conditions).
This means if you have multiple calls to app.UseStaticFiles()
, it will insert StaticFileMiddleware
in the middleware chain more than once and only the first one in the chain will handle the request, the rest will stay dormant.
Put a breakpoint inside a controller action and check the call stack and see if there are more than one StaticFileMiddleware
in the stack. If you do, remove the unused ones, or move the configuration you have here into the first one.
In your code, you seem to have app.UseSpaStaticFiles
, which calls app.UseStaticFiles
, so it's taking effect before your own app.UseStaticFiles(/*custom options*/)
.
To solve the problem, simply pass the OnPrepareResponse
into that middleware:
app.UseSpaStaticFiles(new StaticFileOptions {
RequestPath = _settings.SpaRoute,
OnPrepareResponse = ctx =>
{
// Cache static files for 30 days
ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=2592000");
}
});