ASP.Net缓存技术
缓存分为页面缓程和应用程序缓存
1.页面缓存
。整页缓存
<%@ OutputCache Duration="5" VaryByParam="none" %>
*缓存标记 * 缓存周期时间 *缓存改变的条件
<%@ OutputCache Duration="30" VaryByControl="DropDownList1" %>
*表示随着DropDownList1值的变化而变化
<%@ OutputCache Duration="5" VaryByParam="cid" %>
*缓存将随着QueryString参数cid的变化而刷新
。页面部分缓存
<%@ OutputCache Duration="30" VaryByParam="none" %>
在页面中添加一个 Substitution控件(占位符)
在后台写一个static静态反回值为string,参数为HttpContext方法
public static string GetTime(HttpContext context)
{
return DateTime.Now.ToLongTimeString();
}
将该方法绑定到Substitution占位符控件属性MethodName中
2.应用程序缓存
在A.aspx中添加一个Gridview和一个链接到B.aspx页面的LinkButton
A.aspx后面代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BinderToGridView();
}
}
private void BinderToGridView()
{
//向服务器请求数据
SqlConnection sqlcon = new SqlConnection("server=.;uid=sa;pwd=;database=NorthWind");
sqlcon.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Product",sqlcon);
DataSet ds = new DataSet();
sda.Fill(ds,"p");
sqlcon.Close();
//将数据存入本地内存
Cache.Insert("NorthWind", ds);
//在Default5.aspx中显示数据
this.GridView1.DataSource = ds.Tables["p"].DefaultView;
this.GridView1.DataBind();
}
B.aspx页面的代码
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds=Cache.Get("NorthWind") as DataSet;
if(ds==null)
{
Response.Write("本地缓存中不存在类似的数据");
Response.Redirect("Default5.aspx");
}
else
{
this.GridView1.DataSource = ds.Tables["p"].DefaultView;
this.GridView1.DataBind();
}
}