【发布时间】:2020-11-15 07:07:46
【问题描述】:
我正在尝试使用 StaticFileOptions 将长缓存标头添加到静态 .css 和 .js 文件中
从各种 SO 和其他文章中,您可以这样做:
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
const int durationInSeconds = 60 * 60 * 24;
ctx.Context.Response.Headers[HeaderNames.CacheControl] =
"public,max-age=" + durationInSeconds;
}
});
但是,我使用的是 RCL 提供的一堆静态文件。 RCL 有一个我在本文中使用的 StaticServing.cs 类:Can Razor Class Library pack static files (js, css etc) too?
为了我的问题的完整性,这个类如下:
public StaticServing(IHostingEnvironment environment)
{
Environment = environment;
}
public IHostingEnvironment Environment { get; }
public void PostConfigure(string name, StaticFileOptions options)
{
name = name ?? throw new ArgumentNullException(nameof(name));
options = options ?? throw new ArgumentNullException(nameof(options));
// Basic initialization in case the options weren't initialized by any other component
options.ContentTypeProvider = options.ContentTypeProvider ?? new FileExtensionContentTypeProvider();
if (options.FileProvider == null && Environment.WebRootFileProvider == null)
{
throw new InvalidOperationException("Missing FileProvider.");
}
options.FileProvider = options.FileProvider ?? Environment.WebRootFileProvider;
string basePath = "Static";
ManifestEmbeddedFileProvider filesProvider = new ManifestEmbeddedFileProvider(GetType().Assembly, basePath);
options.FileProvider = new CompositeFileProvider(options.FileProvider, filesProvider);
}
}
在消费项目 startup.cs 中,我有 services.ConfigureOptions(typeof(StaticServing));,而 RCL 有 <GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest> 和 <EmbeddedResource Include="Static\**\*" /> 设置。
一切就绪后一切正常... 除非我在问题的开头添加了StaticFileOptions 代码,在这种情况下,所有对嵌入式静态文件的引用都返回404 .
我已尝试添加:
-
FileProvider = env.ContentRootFileProvider和 FileProvider = env.WebRootFileProvider
到StaticFileOptions 设置,但这不起作用。
【问题讨论】:
标签: c# asp.net-core .net-core razor-class-library