现在的位置: 首页 > 综合 > 正文

系统缓存全解析2:页面输出缓存

2012年06月12日 ⁄ 综合 ⁄ 共 2225字 ⁄ 字号 评论关闭

页面输出缓存是最为简单的缓存机制,该机制将整个ASP.NET页面内容保存在服务器内存中。当用户请求该页面时,系统从内存中输出相关数据,直到缓存数据过期。在这个过程中,缓存内容直接发送给用户,而不必再次经过页面处理生命周期。通常情况下,页面输出缓存对于那些包含不需要经常修改内容的,但需要大量处理才能编译完成的页面特别有用。需要读者注意的是,页面输出缓存是将页面全部内容都保存在内存中,并用于完成客户端请求。

ASP.NET中页面缓存的使用方法非常的简单,只需要在aspx页的顶部加这样一句声明即可:

 

 

 

<%@ OutputCache Duration="60" VaryByParam="none" %>

 

Duration  

缓存的时间(秒)。这是必选属性。如果未包含该属性,将出现分析器错误。

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CacheWebApp._16_4_3.WebForm1" %>

<%@ OutputCache Duration="60" VaryByParam="none" %>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>页面缓存示例</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    </div>

    </form>

</body>

 

</html>

 

 

       

后台代码:

       protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                Label1.Text = DateTime.Now.ToString();

            }

 

        }

       

    如果不加<%@ OutputCache Duration="60" VaryByParam="none" %>,每次刷新页面上的时间每次都是在变。而加了缓存声明以后,每次刷新页面的时间并不变化,60秒后才变化一次,说明数据被缓存了60秒。

 

VaryByParam

是指页面根据使用 POST GET 发送的名称/值对(参数)来更新缓存的内容,多个参数用分号隔开。如果不希望根据任何参数来改变缓存内容,请将值设置为 none。如果希望通过所有的参数值改变都更新缓存,请将属性设置为星号 (*)

例如: http://localhost:1165/16-4-3/WebForm1.aspx?p=1
则可以在WebForm1.aspx页面头部声明缓存:<%@ OutputCache Duration="60" VaryByParam="p" %>

以上代码设置页面缓存时间是60秒,并根据p参数的值来更新缓存,即p的值发生变化才更新缓存。

如果一直是WebForm1.aspx?p=1访问该页,则页面会缓存当前数据,当p=2时又会执行后台代码更新缓存内容。

 

如果有多个参数时,如:http://localhost:1165/16-4-3/WebForm1.aspx?p=1&n=1

可以这样声明:<%@ OutputCache Duration="60" VaryByParam="p;n" %> 

 

除此之外,@OutputCache 还有一些其他的属性。@OutputCache指令中的属性参数描述如下:

 

<%@ OutputCache Duration="#ofseconds"

   Location="Any | Client | Downstream | Server | None |

     ServerAndClient "

   Shared="True | False"

   VaryByControl="controlname"

   VaryByCustom="browser | customstring"

   VaryByHeader="headers"

   VaryByParam="parametername"

   CacheProfile="cache profile name | ''"

   NoStore="true | false"

   SqlDependency="database/table name pair | CommandNotification"

 

%>

 

 

 

 

 

CacheProfile

用于调用Web.config配置文件中设置的缓存时间。这是可选属性,默认值为空字符 ("")

例如:

Web.config中加入配置:

<system.web>

    <caching>

        <outputCacheSettings>

            <outputCacheProfiles>

                <add name="CacheTest" duration="50" />

            </outputCacheProfiles>

        </outputCacheSettings>

 

 

</caching>

 

 

 

 

抱歉!评论已关闭.