【问题标题】:ServiceStack 4: not able to add Expires Header for static contentServiceStack 4:无法为静态内容添加 Expires Header
【发布时间】:2014-10-26 09:54:23
【问题描述】:

在我的 web.config 中,我正在尝试为静态内容添加缓存:

<system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseExpires" httpExpires="Sun, 1 Jan 2020 00:00:00 UTC" />
    </staticContent>
    <modules runAllManagedModulesForAllRequests="true" />
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
    </handlers>
  </system.webServer>

但是,当我运行 YSlow 时!我仍然得到“添加过期标题”的 F 级;因此,似乎图像、CSS 和 Javascript 文件等静态内容没有被缓存。

我如何在 ServiceStack 中完成此操作,因为我所做的 web.config 更改不会被 ServiceStack 接收;这在 ASP.NET MVC 中确实有效,但是如何使用过期标头服务器静态内容?

我也试过了,但我的静态文件仍然没有被缓存。

<system.webServer>
  <staticContent>
    <clientCache cacheControlMaxAge="30.00:00:00" cacheControlMode="UseMaxAge"/>
  </staticContent>
</system.webServer>

【问题讨论】:

    标签: caching servicestack static-content expires-header servicestack-razor


    【解决方案1】:

    注意:&lt;staticContent&gt; xml 配置对提供自己的静态文件处理功能(如 ServiceStack)的 Web 框架没有影响。

    ServiceStack 中的静态文件由 StaticFileHandler 处理,它会自动附加 HTTP 标头,用于缓存静态文件,例如 Last-Modified 标头,用于发送空的 304 Not Modified 响应,当对没有的静态文件发出请求时自上次请求以来没有更改。

    为静态文件添加 Max-Age

    此外,还有一个选项可以为特定文件类型指定Cache-Control: max-age={Seconds},默认情况下包括图像内容类型的最大年龄,例如:

    SetConfig(new HostConfig {
        AddMaxAgeForStaticMimeTypes = {
            { "image/gif", TimeSpan.FromHours(1) },
            { "image/png", TimeSpan.FromHours(1) },
            { "image/jpeg", TimeSpan.FromHours(1) },
        }
    });
    

    您还可以使用其他内容类型修改和扩展上述默认值。

    添加自定义静态文件头

    v4.0.33+ 中的新功能是 StaticFileHandler.ResponseFilter,您可以使用它在静态文件上附加您自己的自定义标头,例如,这会为 .txt 文件添加自定义 HTTP Expires 标头1 小时后到期:

    StaticFileHandler.ResponseFilter = (req, res, file) => {
        if (file.Extension == "txt")
            res.AddHeader("Expires", DateTime.UtcNow.AddHours(1).ToString("r"));
    };
    

    此更改现在是 available on MyGet

    【讨论】:

      猜你喜欢
      • 2010-10-26
      • 2011-07-13
      • 2011-12-04
      • 1970-01-01
      • 2018-07-28
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多