Set static assets as cacheable in Kentico Xperience 13 .NET Core site

I’m trying to use the following code in a .NET Core site running Kentico Xperience 13.

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = context =>
    {
        context.Context.Response.Headers[HeaderNames.CacheControl] = staticFileCacheHeaderValue;
    },
    HttpsCompression = HttpsCompressionMode.Compress
});

This works, in that my static files under wwwroot get their cache-control header (& gzip compression) set.

However, with this code in place, the page builder and form builder scripts and styles no longer load, giving a 404. E.g., in form builder it’s supposed to load this file: /Kentico/Scripts/builders/builder.css. Anything which begins /Kentico or /_content suddenly 404s.

This happens whatever I pass as the StaticFileOptions – even a simple new StaticFileOptions().

I’ve tried calling app.UseKentico() both before and after, and this doesn’t make a difference. If I call app.UseStaticFiles() as well as the above, there are no Kentico errors, but the wwwroot files don’t get a cache header applied (nor are they compressed).

I’m not very familiar with .NET Core, so I’m not sure if I’m missing something on that side of things, or whether Kentico is just not playing nicely yet. Any help is, of course, great appreciated!

Answer

It is necessary to set cache-control in the given middleware:

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions

{

    OnPrepareResponse = ctx => ctx.Context.Response.Headers.Append(HeaderNames.CacheControl, $"public, max-age={60 * 60 * 24 * 365}"),

    FileProvider = new PhysicalFileProvider(Path.Combine(Environment.ContentRootPath, @"Content")),

    RequestPath = new PathString("/Content")

});

Or if I want to set it for the default app.UseStaticFiles(), it is necessary to setup it in ConfigureServicesmethod in Startup.cs via services.Configure :

services.Configure<StaticFileOptions>(options =>
{
    options.OnPrepareResponse = ctx => ctx.Context.Response.Headers.Append(HeaderNames.CacheControl, $"public, max-age={60 * 60 * 24 * 365}");
});