[英]Using StaticFileOptions() breaks embedded static files from Razor Class Library
我正在嘗試使用StaticFileOptions
將長緩存標頭添加到 static.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 提供的一堆 static 文件。 The RCL has a StaticServing.cs class which I have used from this article: Can Razor Class Library pack static files (js, css etc) too?
為了完整起見,這個 class 如下:
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
代碼,在這種情況下,對嵌入式 static 文件的所有引用都返回404
。
我試過添加:
FileProvider = env.ContentRootFileProvider
和FileProvider = env.WebRootFileProvider
到StaticFileOptions
設置,但這不起作用。
static 文件中間件可以通過以下兩種方式之一接收其StaticFileOptions
:
UseStaticFiles
。 在您的問題場景中,您(無意中)嘗試使用這兩種方法配置中間件。 向UseStaticFiles
調用添加參數后,您將替換框架提供的中間件配置,其中包括 RCL 支持的設置。
要構建框架提供的配置,您可以利用ConfigureServices
中的選項模式:
services.Configure<StaticFileOptions>(options =>
{
options.OnPrepareResponse = ctx =>
{
const int durationInSeconds = 60 * 60 * 24;
ctx.Context.Response.Headers[HeaderNames.CacheControl] =
"public, max-age=" + durationInSeconds;
}
});
您還需要刪除傳遞給UseStaticFiles
的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.