代码阅读总结之Fitch and Mather 7.0(自定义字符串缓存页)
前段时间工作比较忙,没时间读代码,这几天有空,正好又来静读代码了.
在Menus_ascx中我们看到用了缓存自定义字符串"authenticated"
<%@ OutputCache Duration="86400" VaryByParam="None" VaryByCustom="authenticated" %>
注意: @OutputCache 指令与必需的 Duration 和 VaryByParam 属性包括在一起。必须将 Duration 属性设置为大于零的任意整数。如果不想使用 VaryByParam 属性提供的功能,请将其值设置为 None
在Global.asax文件中重写GetVaryByCustomString方法
此处是根据用户是否验证来缓存用户控件,即一个通过验证的用户控件,一个未验证的用户控件
1
public override string GetVaryByCustomString(HttpContext context, string custom)
2
{
3
// There are two different possible caching cases here so we return a different string in each one.
4
if(context.Request.IsAuthenticated)
5
{
6
// Request is authenticated
7
return "B";
8
}
9
else
10
{
11
// Request is not authenticated
12
return "C";
13
}
14
}

2

3

4

5

6

7

8

9

10

11

12

13

14

根据此思路我们可以开发一个依浏览器类型不同的缓存页面的例子
例如我们现有页面WebForm3.aspx,我们可以根据访问着的浏览器类型来做页面缓存
首先在页面中加入
<%@ OutputCache Duration="600" VaryByParam="none" VaryByCustom="ietype" %>
如果定义了自定义字符串,必须在应用程序的 Global.asax 文件中重写 HttpApplication.GetVaryByCustomString 方法
1
public override string GetVaryByCustomString(HttpContext context, string custom)
2
{
3
string browserType=context.Request.Browser.Type;
4
5
//custom自定义字符串,它指定哪个缓存的响应被用于响应当前请求
6
//有可能多个页面都定义了自定义字符串,这时可以依靠参数custom来具体区分
7
if ( custom=="ietype" )
8
if ( browserType=="IE6" )
9
//IE6浏览器返回字符
10
return browserType;
11
else
12
if ( browserType=="Opera7" )
13
//Opera7浏览器返回字符
14
return browserType;
15
else
16
//其他类型的浏览器返回字符
17
return browserType;
18
19
return browserType;
20
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

这样设置好后,
当我用IE6访问页面WebForm3.aspx时,服务器缓存这个类型浏览器的页面600秒
当我再用Opera7.54访问页面WebForm3.aspx时,服务器又缓存这个类型浏览器的页面600秒
我的系列文章
A.Sql Server2005 Transact-SQL 新兵器学习 B.MCAD学习
C.代码阅读总结
D.ASP.NET状态管理
E.DB(数据库)
F.WAP
G.WinForm
H.Flex
希望上面提到的知识对您有所提示,同时欢迎交流和指正
作者:aierong
出处:http://www.cnblogs.com/aierong
贴子以"现状"提供且没有任何担保,同时也没有授予任何权利!
本文版权归作者所有,欢迎转载!
原创技术文章和心得,转载注明出处!这也是对原创者的尊重!