萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET OutputCache 頁面輸出快取完整解析與實戰技巧

ASP.NET @OutputCache 指令提供聲明式頁面/使用者控制項層級的輸出快取,能大幅降低資料庫存取與渲染運算。本文詳細解析各屬性用法、VaryByParam 進階變體、自訂快取鍵策略,以及常見陷阱與最佳實踐。

基本語法與常用屬性

<%@ OutputCache Duration="120" VaryByParam="id" Location="Server" %>
屬性說明典型值
Duration快存秒數60~3600
VaryByParam依查詢字串/表單參數建立不同快取版本"id", "category;page", "none", "*"
VaryByHeader依 HTTP 標頭建立版本(如 User-Agent、Accept-Language)"User-Agent", "Accept-Language"
VaryByCustom自訂快取鍵邏輯,需在 Global.asax 覆寫 GetVaryByCustomString"browser", "userRole"
Location快取位置Any | Client | Server | None | ServerAndClient
NoStore輸出 Cache-Control: no-store,禁止任何快取true/false
CacheProfile引用 web.config 定義的快取設定檔"LongCache"

VaryByParam 進階場景

  • VaryByParam="id":/Product.aspx?id=1 與 id=2 分別快取。
  • VaryByParam="category;page":多參數組合,順序不影響。
  • VaryByParam="*":所有參數組合皆建立獨立快取(慎用,易造成快取爆炸)。
  • VaryByParam="none":忽略參數,整頁共用一份快取(適合純靜態內容)。

VaryByCustom 自訂快取鍵實作

在 Global.asax.cs 覆寫:

public override string GetVaryByCustomString(HttpContext context, string custom) {
    if (custom == "browser") {
        return context.Request.Browser.Browser + context.Request.Browser.MajorVersion;
    }
    if (custom == "userRole") {
        return context.User.IsInRole("Admin") ? "Admin" : "User";
    }
    return base.GetVaryByCustomString(context, custom);
}

頁面指令:VaryByCustom="browser;userRole",即可為不同瀏覽器版本、角色各自快取。

CacheProfile 集中管理

web.config 定義:

<system.web>
  <caching>
    <outputCacheSettings>
      <outputCacheProfiles>
        <add name="LongCache" duration="3600" varyByParam="id" location="Server" />
        <add name="ShortCache" duration="60" varyByParam="none" location="ServerAndClient" />
      </outputCacheProfiles>
    </outputCacheSettings>
  </caching>
</system.web>

頁面引用:CacheProfile="LongCache",修改設定無需改動 .aspx。

常見陷阱與對策

  1. 個人化內容被快取:登入狀態、購物車等用戶專屬資料切勿整頁快取,改用 Substitution 控制項或 VaryByCustom="userRole" 區分。
  2. POST 請求被快取:OutputCache 僅快取 GET/HEAD,POST 會略過,但若 Action 同時支援 GET/POST 需注意。
  3. 快取未失效:資料更新後需手動移除:HttpResponse.RemoveOutputCacheItem("/Product.aspx") 或使用 SqlCacheDependency。
  4. 開發環境干擾:web.config 設 debug="true" 會停用 OutputCache,部署時必須設 false。

效能監控指標

  • 快取命中率:Performance Counter: ASP.NET Applications / Output Cache Hit Ratio
  • 快取項目數/記憶體佔用
  • 平均回應時間對比(快取前/後)

善用 OutputCache 並配合合理的 VaryBy* 策略,能以最低成本獲得顯著效能提升;關鍵在於「精準識別可快取內容」與「建立可靠的失效機制」。

copyright © 萬盛學電腦網 all rights reserved