科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道ASP.NET 2.0中的页面输出缓存 3

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

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

如图1所示,应用程序初始显示的是停止执行缓存的时间。

作者:中国IT实验室 来源:中国IT实验室 2007年9月6日

关键字: 缓存 ASP.NET

  • 评论
  • 分享微博
  • 分享邮件

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

查看本文来源

    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章