1

我正在尝试使用将长缓存头添加到静态 .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设置,但这不起作用。

4

1 回答 1

0

静态文件中间件可以通过StaticFileOptions以下两种方式之一接收它:

  1. 隐式地通过依赖注入。
  2. 显式地通过调用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.

于 2020-07-25T16:25:04.063 回答