繁体   English   中英

ServiceStack 4:无法为静态内容添加Expires Header

[英]ServiceStack 4: not able to add Expires Header for static content

在我的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文件)没有被缓存。

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

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

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

注意: <staticContent> xml配置对提供自己的静态文件处理功能(如ServiceStack)的Web框架无效。

ServiceStack中的静态文件由StaticFileHandler处理,该文件会自动附加HTTP标头,可用于缓存静态文件,如Last-Modified标头,当对静态文件进行更改以来对它们没有任何更改时,该标头用于发送空的304 Not Modified Response。最后要求。

将最大年龄添加到静态文件

此外,还有一个选项可以为特定文件类型指定Cache-Control: max-age={Seconds} ,默认情况下,其中包括Image Content-Types的最大期限,例如:

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"));
};

现在, 可以在MyGet上使用此更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM