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

本文详细介绍了如何在ASP.NET应用中实现缓存时间的动态更新与服务器响应的控制,通过@OutputCache指令和Page_Load事件处理程序,实现页面输出缓存功能,以及根据查询字符串参数动态调整缓存策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

如图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指令的配置内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值