如何为ASP.NET MVC Web应用程序中使用的图像添加缓存?

我已经阅读了这篇 http://madskristensen.net/post/add-expires-header-for-imageshttps://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小时/天没有要求,因为这些图像很长时间都不会改变.

我该怎么做呢 ?

解决方法

以下配置应使浏览器将图像缓存整整一年:

<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缓存头指令

您应该创建一个可配置的appsetting,它作为查询字符串参数传递给这样的图像URI.这将允许您清除所有客户端以从服务器发送请求图像:(我们希望控制这个,因为缓存的图像可能有问题)

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

有关缓存标头(Cache-Control)的更多信息,请参见http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/

我希望有所帮助!

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....