【问题标题】:How do I add caching for images used in my ASP.NET MVC web app?如何为 ASP.NET MVC Web 应用程序中使用的图像添加缓存?
【发布时间】:2016-04-16 19:11:09
【问题描述】:

我看过这个http://madskristensen.net/post/add-expires-header-for-images和https://technet.microsoft.com/en-us/library/cc770661.aspx等类似的文章,谁建议放这个

<staticContent>
 <clientCache httpExpires="Sun, 29 Mar 2020 00:00:00 GMT" cacheControlMode="UseExpires" />
</staticContent>

但是即使在这之后图像没有从缓存中获取并且发送了 200 ok 响应,也就是向服务器发出了请求。我不希望在 x 小时/天之内发出任何请求,因为这些图像在很长一段时间内都不会改变。

我该怎么做?

【问题讨论】:

    标签: asp.net asp.net-mvc caching iis


    【解决方案1】:

    以下配置应该会导致浏览器将您的图像缓存一整年:

    <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
    </staticContent>
    <httpProtocol>
        <customHeaders>
            <add name="Cache-Control" value="public" />
        </customHeaders>
    </httpProtocol>
    

    您只需要确保您的图片是作为静态文件类型提供的。没有办法强制浏览器不向服务器发送请求,即;用户执行硬刷新。

    您可以将上述配置包装在位置节点中,以便仅影响位于特定路径中的图像:

       <location path="Content">
                <system.webServer>
                  <staticContent>
                    <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
                  </staticContent>
                  <httpProtocol>
                    <customHeaders>
                        <add name="Cache-Control" value="public" />
                    </customHeaders>
                  </httpProtocol>
                </system.webServer>
        </location>
    

    上述配置将为http://www.example.com/Content/Images/* 托管的所有图像添加一个 HTTP 缓存标头指令

    您应该创建一个可配置的应用设置,将其作为查询字符串参数传递到此类图像 URI。这将允许您清除所有客户端以从您的服务器发送图像请求:(我们希望对此进行控制,因为缓存的图像可能会出现问题)

    <img src="/Content/Images/MyImage.jpg?version=<%# Global.ImageVersion %>" />
    

    更多关于缓存头(Cache-Control)的信息在这里http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      Asp.net Mvc 页面Index.cshtml:

      <div class="title">
          <img src="../../Content/title.png?ver=@DateTime.Now.ToString("ssfff")">
      </div>
      

      输出主页/索引:

      <div class="title">
       <img src="../../Content/title.png?ver=13388">
      </div>
      

      这个页面每次都会刷新img src。

      【讨论】:

      • 目标是缓存图片,不需要每次都重新加载。
      猜你喜欢
      • 2010-09-16
      • 2019-02-13
      • 1970-01-01
      • 2023-04-08
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      相关资源
      最近更新 更多