您的位置:首页 > 编程语言 > ASP

ASP.NET 2.0中的页面输出缓存

2008-07-01 12:58 411 查看
如图1所示,应用程序初始显示的是停止执行缓存的时间。当用户刷新页面(URL地址是http://localhost:5159/Code%2012-1/Default.aspx,其中5159是服务器临时端口号)时,时间值将随时变化,以便显示当前的最新时间。如图12-2所示,单击“缓存时间”超链接后,页面重定向到http://localhost:5159/Code%2012-1/Default.aspx?location=beijing。这时,页面显示的时间被缓存,数据过期时间为5秒。如果不断地刷新该页,那么每隔5秒钟时间值才变化一次。    本节示例存在两个关键点。一是在运行时实现停止缓存,二是配置@ OutputCache指令。这两点都已经在应用程序Default.aspx文件中予以实现,下面列举了该文件源代码。

Default.aspx文件源代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ OutputCache Duration="5" VaryByParam="location" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <script language="C# " runat="server"> void Page_Load(object sender, EventArgs e) { // 设置仅将缓存数据存储在服务器上 Response.Cache.SetCacheability(HttpCacheability.Server); string temp_location = Request.QueryString["location"]; // 如果 location 为空 则不缓存 否则根据 @ OutputCache 指令声明执行缓存 if (temp_location == null) { // 停止当前响应的所有服务器缓存 Response.Cache.SetNoServerCaching(); Label1.Text = " 停止缓存的时间 " + DateTime.Now.ToString(); } else { Label1.Text = " 设置了缓存的时间 " + DateTime.Now.ToString(); } } </script> <head id="Head1" runat="server"> <title>示例12-1</title> <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" /> </head> <body> <form id="form1" runat="server"> <div> <fieldset style="width: 240px"> <legend class="mainTitle">设置页面输出缓存</legend> <br /> <center><asp:Label ID="Label1" runat="server" CssClass="commonText"></asp:Label></center> <br /> <a href="Default.aspx?location=beijing" class="littleMainTitle" > 缓存时间 </a> <br /> </fieldset> </div> </form> </body> </html>
   如上粗体代码所示,代码头部的@ OutputCache指令设置了Duration和VaryByParam属性,其指示数据过期时间为5秒。同时,缓存根据参数location发生变化。另外,代码还实现了Page_Load事件处理程序。在该程序中,首先,使用SetCacheability方法设置数据缓存必须存储在服务器上,然后,获取QueryString的location参数值,最后,根据location参数值进行判断。如果location参数值为空,则调用SetNoServerCaching方法停止当前响应的所有服务器缓存,并显示当前时间值。虽然@ OutputCache指令配置了页面输出缓存,但是,不会执行页面输出缓存功能。如果location参数值不为空,则直接显示当前时间值。在这种情况下,将执行@ OutputCache指令的配置内容
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: