惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
MongoDB | Blog
MongoDB | Blog
Engineering at Meta
Engineering at Meta
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
T
The Exploit Database - CXSecurity.com
P
Privacy & Cybersecurity Law Blog
Know Your Adversary
Know Your Adversary
月光博客
月光博客
I
InfoQ
阮一峰的网络日志
阮一峰的网络日志
NISL@THU
NISL@THU
爱范儿
爱范儿
S
Securelist
博客园 - 叶小钗
C
CERT Recently Published Vulnerability Notes
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
D
DataBreaches.Net
G
GRAHAM CLULEY
P
Proofpoint News Feed
A
About on SuperTechFans
Google DeepMind News
Google DeepMind News
C
Cyber Attacks, Cyber Crime and Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tor Project blog
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Recent Announcements
Recent Announcements
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
The Cloudflare Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
Jina AI
Jina AI
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
罗磊的独立博客
博客园 - 【当耐特】
H
Help Net Security
F
Fortinet All Blogs
T
The Blog of Author Tim Ferriss

博客园 - 张远强

原版SQLHelper.cs下载 Chrome浏览器Proxy Switchy、Tampermonkey等扩展程序下载 GreaseMonkey脚本:阻止Google转换搜索链接地址 站在31岁,理解程序员年过三十这道坎 GreaseMonkey让网站登录验证码形同虚设 DateTime.ToString格式限定符转义 借Windows说明Linux分区和挂载点 JSON解析类(C#) 彻底解决ASP.NET MD5加密中文结果和ASP不一致的问题 SharpZipLib使用示例 DotNetZip使用示例 Dvbbs 8.2.0 RC1多功能编辑器,提供下载 B/S系统版本管理V1.0正式发布 个人网站与动网整合步骤(支持PDO1.0) - 张远强 - 博客园 C#中显/隐式实现接口及其访问方法 C#接口范例 巧用escape解决ASP.NET中URL传参乱码问题 使用Filter实现信息的二次检索 使用overflow代替left截取指定长度字符串
ASP.NET 2.0缓存
张远强 · 2007-12-27 · via 博客园 - 张远强

一、页输出缓存

1.设置 ASP.NET 页缓存的两种方式

1.1 以声明方式设置 ASP.NET 页的缓存

以声明方式设置 ASP.NET 页的缓存的方法是在页中使用 @ OutputCache 指令,它的常用属性如下:

1<%@ OutputCache Duration="" VaryByParam="" VaryByControl=""
       VaryByHeader
="" VaryByCustom="" CacheProfile="" Location="" %>

Duration:设置缓存到期时间,单位:秒。
VaryByParam:可用来使缓存输出因查询字符串而异,多个查询字符用分号隔开。
VaryByControl:可用来使缓存输出因控制值而异。
VaryByHeader:可用来使缓存输出因请求的 HTTP 标头而异。
VaryByCustom:可用来使缓存输出因浏览器类型或您定义的自定义字符串而异。
CacheProfile:结合配置文件使用。
Location:设置页的可缓存性,值有Any,Client,Downstream,None,Server,ServerAndClient。

注:

在使用 @ OutputCache 指令时,必须包括一个 VaryByParam 属性,否则将出现分析器错误。如果不希望使用 VaryByParam 属性提供的功能,请将它的值设置为“None”。

@ OutputCache 指令使用示例

①使用参数对页的各个版本进行缓存:

1<%@ OutputCache Duration="60" VaryByParam="City" %>

注:如果要根据多个参数改变输出缓存,请包括以分号 (;) 作为分隔符的参数名称的列表;如果要根据所有的参数值来改变缓存,请将VaryByParam 属性设置为星号 (*);如果不要根据参数值来改变缓存,请将 VaryByParam 属性设置为"None"。

②使用 HTTP 标头对某页的各个版本进行缓存:

<%@ OutputCache Duration="60" VaryByParam="None" VaryByHeader="Accept-Language" %>

注:如果要根据多个标头改变缓存的内容,请以分号 (;) 作为分隔符包括标头名称的列表;如果要根据所有标头值改变缓存的内容,请将VaryByHeader 属性设置为星号 (*)。

③使用请求浏览器缓存页的各个版本:

1<%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="browser" %>

④使用自定义字符串对页的各个版本进行缓存:

1<%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="minorversion" %>

注:还要在应用程序的 Global.asax 文件中,重写 GetVaryByCustomString 方法以指定自定义字符串的输出缓存行为。参考:http://msdn2.microsoft.com/zh-cn/library/5ecf4420(VS.80).aspx

⑤结合配置文件:
将以下 XML 添加为 system.web 元素的子项:

1<!-- caching section group -->
2<caching>
3<outputCacheSettings>
4    <outputCacheProfiles>
5        <add name="AppCache1" enabled="true" duration="60"/>
6    </outputCacheProfiles>
7</outputCacheSettings>
8</caching>

@ OutputCache 指令:

1<%@ OutputCache CacheProfile="AppCache1" VaryByParam="None" %>

使用这种方法我们可以从单个配置文件更改缓存行为,而无需编辑各个页面的 @ OutputCache 指令,并且还可以根据需要建立不同的缓存规则,再应用到各组单独页面中。

1.2 以编程方式设置 ASP.NET 页的缓存

以编程方式设置 ASP.NET 页的缓存的方法是在页的代码中,调用 Response 对象的 Cache 属性:

1Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); //设置缓存过期时间
2Response.Cache.SetCacheability(HttpCacheability.Public); //设置页的可缓存性
3Response.Cache.SetValidUntilExpires(true); //缓存忽略 Cache-Control 无效标头

使用示例

①使用参数对页的各个版本进行缓存:

1protected void Page_Load(object sender, EventArgs e)
2{
3    Response.Cache.SetExpires(DateTime.Now.AddMinutes(1.0));
4    Response.Cache.SetCacheability(HttpCacheability.Public);
5    Response.Cache.SetValidUntilExpires(true);
6    Response.Cache.VaryByParams["Zip"= true;
7}

注:如果要根据多个参数改变缓存的内容,请多次设置 VaryByParams 属性。

②使用 HTTP 标头对某页的各个版本进行缓存:

1protected void Page_Load(object sender, EventArgs e)
2{
3    Response.Cache.SetExpires(DateTime.Now.AddMinutes(1.0));
4    Response.Cache.SetCacheability(HttpCacheability.Public);
5    Response.Cache.SetValidUntilExpires(true);
6    Response.Cache.VaryByHeaders["Accept-Language"= true;
7}

注:如果要根据多个标头改变缓存的内容,需要在 VaryByHeaders 属性中设置多个值。如果要根据所有标头改变缓存的内容,请将VaryByHeaders["VaryByUnspecifiedParameters"] 设置为 true。

③使用请求浏览器缓存页的各个版本:

1protected void Page_Load(object sender, EventArgs e)
2{
3    Response.Cache.SetExpires(DateTime.Now.AddMinutes(1.0));
4    Response.Cache.SetCacheability(HttpCacheability.Public);
5    Response.Cache.SetValidUntilExpires(true);
6    Response.Cache.SetVaryByCustom("browser");
7}

④使用自定义字符串对页的各个版本进行缓存:

1protected void Page_Load(object sender, EventArgs e)
2{
3    Response.Cache.SetExpires(DateTime.Now.AddMinutes(1.0));
4    Response.Cache.SetCacheability(HttpCacheability.Public);
5    Response.Cache.SetValidUntilExpires(true);
6    Response.Cache.SetVaryByCustom("minorversion");
7}

说明:要在应用程序的 Global.asax 文件中,重写 GetVaryByCustomString 方法以指定自定义字符串的输出缓存行为。

2.页输出缓存的几种模型

2.1 整页缓存:当设置 ASP.NET 页缓存的位置发生在页面上时,即是整页缓存。
2.2 部分页缓存(控件缓存):当设置 ASP.NET 页缓存的位置发生在用户控件上时,即是控件缓存。
2.3 部分页缓存(缓存后替换):在整个缓存的页面上以声明方式使用 Substitution 控件或以编程方式使用 Substitution 控件 API 或以隐式方式使用 AdRotator 控件,即是采用了缓存后替换。

缓存后替换举例(以声明方式使用 Substitution 控件)

aspx代码:

1<asp:Label ID="Label1" runat="server" Text="Label" Width="276px"></asp:Label>
2<br />
3<asp:Substitution ID="Substitution1" runat="server" MethodName="NoCache" />

aspx.cs代码:

1protected void Page_Load(object sender, EventArgs e)
2{
3    Label1.Text = DateTime.Now.ToString();
4}

5protected static string NoCache(HttpContext context)
6{
7    return DateTime.Now.ToString();
8}

说明:Substitution 控件的 MethodName 属性值为一个方法的名称(本例为NoCache),对该方法的要求是它接受的参数类型必须为HttpContext且返回值类型为string,而且还必须为静态方法!

二、应用程序缓存

1.创建

方法1:Cache["CacheName"] = "CacheValue";
方法2:Cache.Insert("CacheName","CacheValue","缓存依赖","绝对过期时间","弹性过期时间","优先级","");
方法3:Cache.Add("CacheName","CacheValue","缓存依赖","绝对过期时间","弹性过期时间","优先级","");

Add方法和Insert方法的区别是Add 方法将返回您添加到缓存中的对象。另外,如果使用 Add 方法,并且缓存中已经存在与现有项同名的项,则该方法不会替换该项,并且不会引发异常。

创建示例

①通过使用 Insert 方法将项添加到缓存中:

1Cache.Insert("CacheItem2""Cached Item 2");

②通过指定依赖项向缓存添加项:

1string[] dependencies = "CacheItem2" };
2Cache.Insert("CacheItem3""Cached Item 3",
new
 System.Web.Caching.CacheDependency(null, dependencies));

③将设有过期策略的项添加到缓存中:

1Cache.Insert("CacheItem6""Cached Item 6",null, DateTime.Now.AddMinutes(1d),
System.Web.Caching.Cache.NoSlidingExpiration);

④将设有优先级设置的项添加到缓存中:

1Cache.Insert("CacheItem8""Cached Item 8",
2    null, System.Web.Caching.Cache.NoAbsoluteExpiration,
3    System.Web.Caching.Cache.NoSlidingExpiration,
4    System.Web.Caching.CacheItemPriority.High, null);

2.检索

1string cachedString;
2cachedString = (string)Cache["CacheItem"];
3if (cachedString == null)
4{
5  cachedString = "Www.Mzwu.Com";
6  Cache.Insert("CacheItem", cachedString);
7}

注:由于缓存中所存储的信息为易失信息,即该信息可能由 ASP.NET 移除,因此建议的开发模式是首先确定该项是否在缓存中。如果不在,则应将它重新添加到缓存中,然后检索该项。

3.移除

1Cache.Remove("MyData1");

MSDN上缓存概述:http://msdn2.microsoft.com/zh-cn/library/726btaeh%28VS.80%29.aspx