更改Asp.net Core中静态文件的标题

ead*_*dam 10 asp.net-core-mvc asp.net-core

我正在使用包Microsoft.AspNet.StaticFiles并将其配置Startup.csapp.UseStaticFiles().如何更改已传送文件的标题?我想为图像,css和js设置缓存到期等.

Jos*_*uch 18

您可以使用StaticFileOptions,它包含在静态文件的每个请求上调用的事件处理程序.

你的Startup.cs应该是这样的:

// Add static files to the request pipeline.
app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = (context) =>
    {
        // Disable caching of all static files.
        context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store";
        context.Context.Response.Headers["Pragma"] = "no-cache";
        context.Context.Response.Headers["Expires"] = "-1";
    }
});
Run Code Online (Sandbox Code Playgroud)

当然,您可以修改上面的代码来检查内容类型,只修改JS或CSS或任何您想要的标题.

  • 由于这些是.css / .js的静态文件,因此通常应使用适当的时间来缓存,而不要使用“ no-cache,no-store”来提高性能,例如:context.Context.Response.Headers [HeaderNames .CacheControl] =“ public,max-age = 86400”;`(这里的86400是24小时= 24 * 60 * 60秒)。为了在更新文件时强制绕过缓存,我们还可以在<link>,`<script> ... ...标记旁边使用`asp-append-version =“ true”`标记助手。根据将自动更新的文件的哈希值生成查询字符串。 (2认同)

Mat*_*der 7

根据上面 Josh Mouch 的回答,添加了代码来确定它是否是 pdf 文件

启动.cs:

      app.UseStaticFiles(new StaticFileOptions
      {
        OnPrepareResponse = ctx =>
          {
            if(ctx.File.Name.ToLower().EndsWith(".pdf"))
            {
              ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=86400");
            }
            else
            {
              ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=31104000");
            }
          }
      });
Run Code Online (Sandbox Code Playgroud)


Dar*_*eal 5

如果您正在寻找一种解决方案,允许您为每个环境(开发、生产等)配置不同的行为,这也是在 web.config 文件中设置这些设置而不是对整个内容进行硬编码的要点,那么您可以可以考虑以下方法。

在appsettings.json文件中添加以下键/值部分:

  "StaticFiles": {
    "Headers": {
      "Cache-Control": "no-cache, no-store",
      "Pragma": "no-cache",
      "Expires": "-1"
    }
  }
Run Code Online (Sandbox Code Playgroud)

然后在Startup.cs文件的方法中相应添加以下内容Configure

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = (context) =>
    {
        // Disable caching for all static files.
        context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
        context.Context.Response.Headers["Pragma"] = Configuration["StaticFiles:Headers:Pragma"];
        context.Context.Response.Headers["Expires"] = Configuration["StaticFiles:Headers:Expires"];
    }
});
Run Code Online (Sandbox Code Playgroud)

appsettings.json这将允许开发人员使用不同/多个/级联设置文件(appsettings.production.json等等)定义不同的缓存设置- 这可以使用旧web.config配置模式来完成 - 使用 ASP.NET Core 的新配置模式。

有关该主题的更多信息,我还建议阅读我的博客上的这篇文章和/或官方 ASP.NET Core 文档中的这些精彩文章: