ASP.NET 缓存,十--根据自定义字符串缓存页的版本

除了根据浏览器类型改变输出缓存之外,@ OutputCache 指令的 VaryByCustom 属性和 HttpCachePolicy.SetVaryByCustom 方法允许根据您定义的自定义字符串缓存页输出的多个版本。

当选择使用两种技术中的任何一种扩展输出缓存的功能时,您必须在应用程序的 Global.asax 文件中重写 HttpApplication.GetVaryByCustomString 方法。您在重写语句中编写的代码定义应用程序如何缓存根据自定义字符串或您指定的字符串改变的任何页输出。

根据自定义字符串以声明方式缓存页输出的多个版本

  1. 在 .aspx 文件中,将 @OutputCache 指令与必需的 DurationVaryByParam 属性包括在一起。必须将 Duration 属性设置为大于零的任意整数。如果不想使用 VaryByParam 属性提供的功能,请将其值设置为 None
  2. @OutputCache 指令体中包括 VaryByCustom 属性,该属性设置为要根据其改变输出缓存的字符串。下面的指令根据自定义字符串“minorversion”改变页输出。
    <%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="minorversion" %>
  3. 在应用程序的 global.asax 文件的代码声明块中,重写 GetVaryByCustomString 方法来为自定义字符串指定输出缓存的行为。

根据自定义字符串以编程方式缓存页输出的多个版本

  1. 在该页的代码声明块或代码隐藏类中,使用 Response.Cache 语法为已缓存的页面内容设置到期和可见性策略。您可以分别使用 HttpCachePolicy.SetExpiresHttpCachePolicy.SetCacheability 方法来完成此任务。有关更多信息,请参见设置页缓存的到期时间设置页的可缓存性
  2. 在相同的代码中,在 SetVaryByCustom 方法的 custom 参数中指定自定义字符串。以下代码将自定义字符串设置为“minorversion”。
    [C#]
        Response.Cache.SetVaryByCustom("minorversion");
        [Visual Basic]
        Response.Cache.SetVaryByCustom("minorversion")
  3. 在应用程序的 Global.asax 文件的代码声明块中,重写 GetVaryByCustomString 方法来为自定义字符串指定输出缓存的行为。

下面的示例演示一个简单的 Global.asax 文件,当应用程序中某页将自定义字符串 minorversion 传递到该文件时,该文件将重写 GetVaryByCustomString 方法。

[C#]
<script>
public override string GetVaryByCustomString(HttpContext context, string arg){
If (arg = "minorversion"){
Return "Version=" + context.Request.Browser.MinorVersion.ToString();
}
}
</script>
[Visual Basic]
<script>
Public Overrides Function GetVaryByCustomString(context As HttpContext, arg As String) As String
If (arg = "minorversion") Then
return "Version=" & context.Request.Browser.MinorVersion.ToString()
End If
End Function
</script>

下面的示例是一个与前面的 Global.asax 文件交互的页,用于根据 minorversion 自定义字符串改变输出缓存。

注意 此示例页使用声明性语法来改变输出缓存。如果要以编程方式进行此操作,将类似于设置页缓存的到期时间中所显示的代码放置在 <script> 元素的开始和结束标记之间。
[C#]
<%@ OutputCache Duration="30" VaryByParam="none" VaryByCustom="minorversion" %>
<Script language="C#" runat="server">
public void Page_Load(Object sender, EventArgs e) {
browserversion.InnerHtml = Request.Browser.MinorVersion.ToString();
timestamp.InnerHtml = DateTime.Now.ToString("r");
}
</Script>
Varying output by custom string (querystring value): <B />
<BR>
Added to the cache: <B  />
[Visual Basic]
<%@ Page Language="VB" %>
<%@ OutputCache Duration="30" VaryByParam="none" VaryByCustom="minorversion" %>
<Script runat="server">
Public Sub Page_Load
browserversion.InnerHtml = Request.Browser.MinorVersion.ToString()
timestamp.InnerHtml = DateTime.Now.ToString("r")
End Sub
</Script>
Varying output by browser: <B />
<BR>
Added to the cache: <B  />

当以不同的值传递到 HttpBrowserCapabilities.MinorVersion 属性值来请求该示例中的页,将为发出请求的每个浏览器缓存页输出的不同版本。例如,来自 Internet Explorer 5 浏览器的请求导致缓存一个版本,而来自 Internet Explorer 5.5 浏览器的请求导致缓存另一个版本。