当前位置: 主页 > 编程知识 > net编程 > ASP.NET学习:缓存的介绍和应用

ASP.NET学习:缓存的介绍和应用

时间:2009-12-10来源:站长资讯网 点击:

自定义缓存(Custom Caching)

你也可以创建自定义的程序来缓存页面。ASP.NET提供了一种很便捷的方式来创建自定义缓存,使用VarByCustom属性指定自定义缓存类型的名字。

你还要创建为缓存生成自定义字符串的方法,如下:

以下为引用的内容:

public override stringGetVaryByCustomString(HttpContext context, stringcustom)
{
    if(custom == "browser")
    {
       returncontext.Request.Browser.Browser +
              context.Request.Browser.MajorVersion;
    }
    else
    {
       return base.GetVaryByCustomString(context, custom);
    }
}

这个方法必须写在global.asax文件中。ASP.NET使用该方法返回的字符串来实现缓存,如果这个方法在不同的请求中返回相同的字符串,ASP.NET就会使用缓存的页面,否则就会生成新的缓存版本。

上面的例子中GetVaryByCustomString()方法根据浏览器的名字创建缓存字符串,ASP.NET会根据不同的浏览器请求创建不同版本的缓存。

控件缓存(Control Cache )

上面的缓存技术可以让你很容易的缓存整个页面,如果要缓存指定控件的内容,可以通过指定VaryByControl 属性来完成。

以下为引用的内容:

%@OutputCacheDuration="20"VaryByControl="MyControl_1"%

上面代码ASP.NET将会缓存MyControl_1控件20分钟。如果要根据一些属性值来缓存控件只需要将OutPutCache指令加入*.ascx页面。

以下为引用的内容:

<%@Control Language="C#"AutoEventWireup="true"CodeFile="MyControl.ascx.cs"
Inherits="Controls_MyControl"%>
<%@OutputCacheDuration="20"VaryByControl="EmployeeID"%>

VaryByControl=”EmployeeID”告诉ASP.NET根据控件中声明的EmployeeID属性来创建不同版本的缓存。

在 .ascx.cs 文件加入EmplyeeID属性为ASP.NET 缓存使用。

在页面中增加控件并且设置 EmployeeID.

以下为引用的内容:

private int_employeeID;

public intEmployeeID
{
   get{ return_employeeID; }
   set{ _employeeID = value; }
}

protected voidPage_Load(objectsender, EventArgs e)
{
   lblDate.Text = DateTime.Now.ToShortDateString();
   lblTime.Text = DateTime.Now.ToLongTimeString();
   lblEmployeeID.Text = EmployeeID.ToString();
}

站长资讯网
.
分页: [1] [2] [3]
TAG: ASP.NET 缓存
推荐内容最近更新人气排行
关于我们 | 友情链接 | 网址推荐 | 常用资讯 | 网站地图 | RSS | 留言