浏览器缓存

缓存是高性能网站的基石,可以达到的目的:

减少往返
将内容移到离客户端更近的地方
避免为重复的内容,花费再次请求的时间

在所有层缓存,一般应用有以下层次:

1、浏览器
2、本地代理-isp代理
3、web服务器中:
    http.sys
    iis输出缓存
    ASP.NET输出缓存
    ASP.NET对象缓存、ASP.NET请求缓存
4、SQLSERVER数据库

我们尽可能合理地在每一层中进行缓存

浏览器缓存

减少服务器之间的往返,缩短相应时间.
缓存静态内容:在http头信息中,cache-control属性表示缓存信息。
设置cache-control属性,可以在IIS管理器中设置cache-control的值,还可以在Web.Config文件中配置:

<system.webserver>
    <staticContent>
        <clientCache cacheControlAge="usage" cacheControlMaxage="365.00:00:00"/>
    </staticContent>
</system.webserver>

在后面还可以为特定的静态资源,设置更短的时间。

关闭游览器缓存

可以为特定的静态资源关闭浏览器缓存,可以在IIS中设置,也可以在Web.Config文件中配置:

<location path="image.jpg">
    <system.webserver>
        <staticContent>
            <clientCache cacheControlMode="DisableCache"/>
        </staticContent>
    </system.webserver>
</location>

缓存动态内容

在ASPX页面中使用声明方式实现缓存,设置过期时间:
<%@outputcache Duration="86400" Location="client" VaryByParam="None"%>
这句话在运行时中会生成Http头,让浏览器缓存86400秒(1天),还必须设置VaryByParam="None"属性,表明该页面的多个版本不需要独立缓存。
还可以通过编程方式设置,在后置代码或者httpModule中:

void SetCache()
{
    this.Response.Cache.SetExpires(DateTime.Now.AddDays(1));//可以忽略
    TimeSpane ds = new TimeSpane(1,0,0,0);
    this.Response.Cache.SetMaxage(ds);//关键代码
}

使用缓存配置
在Web.Config文件中配置一个缓存,然后可以在ASPX里面outputcache中使用:

<system.web>
    <caching>
        <outputcachesetting>
            <outputcacheprofiles>
                <add name="cacheDay" duration="86400" location="client" varyByParam="none"/>
            </outputcacheprofiles>
        </outputcachesetting>
    </caching>
</system.web>

在ASPX页面中:
<%@outputcache cacheprofile="cacheDay"%>
也能达到一样的目的。
关闭缓存
应该只在数据必须时刻保持最新的情况下,关闭缓存。
关闭缓存只能在编程的时候实现:

void SetNoCache()
{
    this.Response.Cache.SetCacheablity(HttpCacheablity.Nocache);//关键代码
}

原文地址:https://www.cnblogs.com/lmfeng/p/2789096.html