如何指定HTTP过期标头?(ASP.NET MVC + IIS)

Mar*_*rek 52 iis asp.net-mvc caching http-headers

我已经在我的ASP.NET MVC应用程序中使用输出缓存.

页面速度告诉我在响应头中为css和图像指定HTTP缓存过期.

我知道Response对象包含一些控制缓存过期的属性.我知道这些属性可以用来控制我从我的代码服务的响应的HTTP缓存:

Response.Expires
Response.ExpiresAbsolute
Response.CacheControl
Run Code Online (Sandbox Code Playgroud)

或者

Response.AddHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
Run Code Online (Sandbox Code Playgroud)

问题是如何为自动提供的资源设置Expires标头,例如images,css等?

Mar*_*rek 77

找到了:

我需要为静态内容指定客户端缓存(在web.config中).

<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlCustom="public" 
      cacheControlMaxAge="12:00:00" cacheControlMode="UseMaxAge" />
    </staticContent>
   </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

来自http://www.iis.net/ConfigReference/system.webServer/staticContent/clientCache

  • 不确定是否有任何区别 - 随意检查HTTP流量的差异:)上述方法的优点是可以在不配置IIS的情况下改变缓存行为(例如,在共享主机上) (3认同)

Dre*_*kes 31

如果你想从你要返回的资源的代码(即不是从IIS提供的静态文件)中做到这一点,你最好使用Response.Cache:

Response.Cache.SetExpires(DateTime.Now.AddYears(1));
Response.Cache.SetCacheability(HttpCacheability.Public);
Run Code Online (Sandbox Code Playgroud)

我知道这并不是你所要求的,但我通过谷歌发现了这个问题,并且其他人可能会喜欢这个答案,因为它与你在原始问题文本中显示的API有关.

  • 不应该是DateTime.UtcNow?如果没有,你能解释一下浏览器如何知道服务器的本地时间是多少?(更新:实际上http://stackoverflow.com/questions/4849744/should-i-use-datetime-now-or-datetime-utcnow-in-httpcookie-expires-and-httpcache回答这个问题) (2认同)