0

在我的 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>
4

1 回答 1

0

注意:<staticContent>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您可以使用它在静态文件上附加您自己的自定义标头,例如,这会为在 1 小时内到期Expires的文件添加自定义 HTTP 标头:.txt

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

此更改现在可在 MyGet 上使用

于 2014-10-26T10:45:46.127 回答