[ASP.NET]Substitution,在Cache的網頁上,設定不Cache的區段

[ASP.NET]Substitution,在Cache的網頁上,設定不Cache的區段

在設定Web Page Cache時,如果有些區段不想要Cache的話,就可以透過Substitution來達到這個功能

用以下的範例來說明,

1.先將Web Page設定成Cache 30秒

<%@ OutputCache Duration="10" VaryByParam="None" %>

2.在Page_Load中Response要Cache的內容出去

Response.Write("Cached" + DateTime.Now.ToString() + "<br/>");

3.另外,透過WriteSubstitution、HttpResponseSubstitutionCallback將不Cache的內容傳出去

Response.WriteSubstitution(new HttpResponseSubstitutionCallback(cb));
{
    return "Dynamic" + DateTime.Now.ToString() + "<br/>";
}

4.也可以直接使用asp:Substitution物件來達到不Cache的效果

<asp:Substitution ID="Substitution1" runat="server" MethodName="cb" />

image

整個範例如下,

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache Duration="10" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Substitution</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <br />
        <asp:Substitution ID="Substitution1" runat="server" MethodName="cb" />
        <asp:Button ID="Button1" runat="server" Text="Button" />

    </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Cached" + DateTime.Now.ToString() + "<br/>");
        Response.WriteSubstitution(new HttpResponseSubstitutionCallback(cb));
    }

    static string cb(HttpContext context)
    {
        return "Dynamic" + DateTime.Now.ToString() + "<br/>";
    }
}

參考資料

Response.WriteSubstitution

Substitution 類別

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^