缓存

来源:互联网 发布:java工程师需要学什么 编辑:程序博客网 时间:2024/05/01 22:34

1。使用页面输出缓存:

可以给页面添加一个<% OutPutCache %>指令

<%@ Page Language="C#" %>
<%@ OutputCache Duration="15" VaryByParam="none"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Cache Page Output</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label id="lblTime"  Runat="server" />
   
    </div>
    </form>
</body>
</html>

 

 void Page_Load()
    {
        lblTime.Text = DateTime.Now.ToString("T");
    }
此时,页面中的时间会在15秒后才更新,当然我们也可以给Duration赋上更大的值,页面绝对不保证缓存到我们指定的时间,当服务器内存资源变低的时候,缓存项目会自动从缓存中移除

VaryByParam允许我们缓存页面的不同版本,如果不想根据参数的值缓存页面的不问版本,那么只要把VaryByParam设为none。

 

2.参数改变缓存

两个特殊的参数:

将VarByParam 设为*:传递到页面的查询字符吕或表单参数的任意变化都会创建一个新版本的页面缓存
none:所有查询字符串和表单参数被忽略,只有一个版本的页面缓存

当将VaryByParam改为参数时,可以通过参数对页面进行缓存,下例针对传入的参数创建页面的不同缓存版本

例:传参页面
<a href ="Detial.aspx?id=1">1</a>
<a href ="Detial.aspx?id=2">2</a>
<a href ="Detial.aspx?id=3">3</a>
<a href ="Detial.aspx?id=4">4</a>

详细页面
<%@ OutputCache Duration="3600" VaryByParam="id" %>
<div>
<%= DateTime.Now.ToString("T") %>
</div>

3.控件变化改变缓存

<%@ Page Language="C#" %>
<%@ OutputCache Duration="3600" VaryByControl="dropCategories" %>
<body>
    <form id="form1" runat="server">
    <div>
    <%= DateTime.Now.ToString("T") %>
    <hr />
    <asp:DropDownList runat="server" ID="dropCategories" AutoPostBack="true">
    <asp:ListItem Value="0">0</asp:ListItem>
    <asp:ListItem Value="1">1</asp:ListItem>
    <asp:ListItem Value="2">2</asp:ListItem>
    <asp:ListItem Value="3">3</asp:ListItem>
    </asp:DropDownList>
    </div>
    </form>
</body>