在 Kentico Xperience 13 .NET Core 站点中将静态资产设置为可缓存

问题描述

我正在尝试在运行 Kentico Xperience 13 的 .NET Core 站点中使用以下代码

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

这是有效的,因为我在 wwwroot 下的静态文件设置了它们的缓存控制标头(和 gzip 压缩)。

然而,有了这段代码页面构建器和表单构建器脚本和样式不再加载,给出 404。例如,在表单构建器中,它应该加载这个文件:/Kentico/Scripts/builders/builder.css .任何以 /Kentico 或 /_content 开头的内容都会突然变成 404。

无论我作为 StaticFileOptions 传递什么,都会发生这种情况 - 即使是简单的 new StaticFileOptions()

我试过在之前和之后调用 app.UseKentico(),这并没有什么区别。如果我像上面一样调用 app.UseStaticFiles(),则不会出现 Kentico 错误,但 wwwroot 文件不会应用缓存标头(也不会压缩)。

我对 .NET Core 不是很熟悉,所以我不确定我是否在这方面遗漏了一些东西,或者 Kentico 是否只是玩得不好。当然,任何帮助都非常感谢!

解决方法

需要在给定的中间件中设置缓存控制:

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")

});

或者如果我想设置为默认的app.UseStaticFiles(),则需要在 Startup.cs 中的 ConfigureServicesmethod 通过 services.Configure :

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