使用 Substitution 控件指定输出缓存网页上要以动态内容替换该控件的部分。Substitution 控件为要缓存大部分内容的页提供了一种缓存局部页的简化解决方案。可以对整页进行输出缓存,然后使用 Substitution 控件指定页中免于缓存的部分。需要缓存的区域只执行一次,然后从缓存读取,直至该缓存项到期或被清除。动态区域则在每次请求页时执行。由于不必对这些部分进行封装以缓存在 Web 用户控件中,因此,此缓存模型简化了主要是静态内容的页的代码。例如,如果页包含静态内容(如新闻报道)和显示广告的 AdRotator 控件,这种情况下,此缓存模型就很有用。新闻报道不会更改,这意味着它们可以缓存。但是,您希望在用户每次请求该页时都显示一条新广告。AdRotator 控件直接支持缓存后替换,无论页是否缓存,都在该页回发时呈现一个新广告。
注意 |
---|
在缓存页包含的用户控件中可以放置 Substitution 控件。但是,在输出缓存用户控件中不能放置 Substitution 控件。 |
Substitution 控件执行时,会调用一个返回字符串的方法。该方法返回的字符串即为要在页中的 Substitution 控件的位置上显示的内容。使用 MethodName 属性指定要在 Substitution 控件执行时调用的回调方法的名称。指定的回调方法必须是包含 Substitution 控件的页或用户控件的静态方法。回调方法的签名必须与接受
若要操作页的输出缓存,可使用
Substitution 控件的另一种使用方法是,使用 HttpResponseSubstitutionCallback 委托实现缓存替换行为。此外,还可以在直接支持缓存替换功能的控件(如 AdRotator 控件)上实现缓存替换行为。有关更多信息,请参见
示例:
<%@ outputcache duration="60" varybyparam="none" %> <script runat="server" language="C#"> void Page_Load(object sender, System.EventArgs e) { // Display the current date and time in the label. // Output caching applies to this section of the page. CachedDateLabel.Text = DateTime.Now.ToString(); } // The Substitution control calls this method to retrieve // the current date and time. This section of the page // is exempt from output caching. public static string GetCurrentDateTime (HttpContext context) { return DateTime.Now.ToString (); } </script> <html> <head runat="server"> <title>Substitution Class Example</title> </head> <body> <form runat="server"> <h3>Substitution Class Example</h3> <p>This section of the page is not cached:</p> <asp:substitution id="Substitution1" methodname="GetCurrentDateTime" runat="Server"> </asp:substitution> <br /> <p>This section of the page is cached:</p> <asp:label id="CachedDateLabel" runat="Server"> </asp:label> <br /><br /> <asp:button id="RefreshButton" text="Refresh Page" runat="Server"> </asp:button> </form> </body> </html>