我正在尝试使用将长缓存头添加到静态 .css 和 .js 文件StaticFileOptions
从各种 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 类:Razor 类库也可以打包静态文件(js、css 等)吗?
为了完整起见,我的问题如下:
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.csservices.ConfigureOptions(typeof(StaticServing));
和 RCL 拥有<GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest>
和<EmbeddedResource Include="Static\**\*" />
设置中。
一切就绪后,一切正常……除非我StaticFileOptions
在问题的开头添加代码,在这种情况下,对嵌入式静态文件的所有引用都返回404
.
我试过添加:
FileProvider = env.ContentRootFileProvider
和FileProvider = env.WebRootFileProvider
到StaticFileOptions
设置,但这不起作用。