頁面輸出快取將完整渲染後的 HTML 直接存入伺服器記憶體,後續請求繞過頁面生命週期直接回應,大幅降低 CPU 與資料庫負載。適用於「資料量大、互動少、內容相對靜態」的頁面(如商品列表、新聞詳情、報表展示)。
| 屬性 | 說明 | 常用值/範例 |
|---|---|---|
| Duration | 快存秒數(必填) | Duration="120" 緩存 2 分鐘 |
| VaryByParam | 依查詢字串/表單參數變化快取(必填) | VaryByParam="id"、VaryByParam="*" (全部)、VaryByParam="none" (不變化) |
| VaryByHeader | 依 HTTP Header 變化快取 | VaryByHeader="User-Agent" 區分裝置 |
| VaryByCustom | 自定義變化邏輯(需覆寫 Global.asax GetVaryByCustomString) | VaryByCustom="browser" 依瀏覽器類型 |
| Location | 快取儲存位置 | Any(預設) | Client | Server | None | ServerAndClient | Downstream |
| CacheProfile | 引用 web.config 定義的快取設定檔 | CacheProfile="LongCache" |
| NoStore | 發送 Cache-Control: no-store | NoStore="true" 防止敏感頁面被快取 |
| VaryByControl | 依使用者控制項屬性變化快取 | VaryByControl="ddlCategory" |
| Enabled | 啟用/停用快取 | Enabled="false" 動態關閉 |
| SqlDependency | SQL 快取依賴字串 | SqlDependency="CommandNotification" |
<%@ OutputCache Duration="120" VaryByParam="none" %>
<%@ OutputCache Duration="120" VaryByParam="id" %>
Product.aspx?id=1 與 id=100 將擁有獨立快取副本。
<%@ OutputCache Duration="300" VaryByParam="category;page;sort" %>
<%@ OutputCache Duration="120" VaryByParam="none" VaryByCustom="browser" %>
需在 Global.asax 實作:
public override string GetVaryByCustomString(HttpContext context, string custom) {
if (custom == "browser") return context.Request.Browser.Type; // 如 "Chrome98", "MobileSafari"
return base.GetVaryByCustomString(context, custom);
}
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="LongCache" duration="3600" varyByParam="id" location="Server" />
<add name="ShortCache" duration="60" varyByParam="*" location="Any" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
頁面引用:<%@ OutputCache CacheProfile="LongCache" %>
| 問題 | 原因 | 解決 |
|---|---|---|
| 使用者看到舊資料 | Duration 過長、未正確設定 VaryByParam | 縮短 Duration、加入關鍵參數、或改用資料快取 + 片段快取 |
| 登入後仍看到登入前頁面 | Location="Client" 或 Proxy 快取 | 設定 Location="Server"、NoStore="true"、或動態關閉快取 |
| Postback 失效 | OutputCache 繞過頁面生命週期,事件不觸發 | 互動頁面勿用整頁快取,改用 <%@ OutputCache ... %> 於 UserControl (片段快取) |
| 記憶體暴增 | VaryByParam="*" 產生大量變體 | 精確指定參數、設定 location="Server" 並監控記憶體 |
<%@ Control Language="C#" %> <%@ OutputCache Duration="60" VaryByParam="categoryId" %> <asp:Repeater ID="rptProducts" runat="server">...</asp:Repeater>
主頁面不快取,僅快取商品列表區塊,兼顧動態與效能。
OutputCache 是 ASP.NET 效能優化的第一道防線。掌握 Duration + VaryByParam 核心組合,善用 CacheProfile 集中管理,結合 片段快取 處理局部動態內容,即可在最小代碼改動下獲得數倍吞吐量提升。