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

时间:2015-03-25 12:53:04

标签: asp.net-core asp.net-core-mvc

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

5 个答案:

答案 0 :(得分:16)

您可以使用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";
    }
});

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

答案 1 :(得分:2)

你必须编写一个中间件才能执行此操作,我已经删除了我的github https://github.com/aguacongas/chatle上的标题的示例了 看看ChatLe.HttpUtility项目,它有点棘手。你也可以看看这个问题:

  

How to do remove some httpresponse headers on each response like Server and ETag?

但是,这不适用于IIS,因为IIS管理静态文件本身。它仅适用于kestrelfirefly

等独立应用

答案 2 :(得分:2)

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

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

  "StaticFiles": {
    "Headers": {
      "Cache-Control": "no-cache, no-store",
      "Pragma": "no-cache",
      "Expires": "-1"
    }
  }

然后在 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"];
    }
});

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

有关该主题的其他信息,我还建议您阅读我的博客上的this post和/或官方ASP.NET核心文档中的这些精彩文章:

答案 3 :(得分:2)

基于Josh Mouch的上述答案,添加了代码以确定它是否为pdf文件

Startup.cs:

 <?php
       defined('YII_DEBUG') or define('YII_DEBUG', true);
       defined('YII_ENV') or define('YII_ENV', 'dev');

答案 4 :(得分:1)

在IIS下,您可以使用标头配置将web.config文件添加到wwwroot文件夹。一个控制所有文件的缓存头的示例:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>

    <!-- Disable caching -->
    <httpProtocol>
      <customHeaders>
        <add name="Cache-Control" value="no-cache" />
      </customHeaders>
    </httpProtocol>

  </system.webServer>
</configuration>