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="id":/Product.aspx?id=1 與 id=2 分別快取。VaryByParam="category;page":多參數組合,順序不影響。VaryByParam="*":所有參數組合皆建立獨立快取(慎用,易造成快取爆炸)。VaryByParam="none":忽略參數,整頁共用一份快取(適合純靜態內容)。在 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",即可為不同瀏覽器版本、角色各自快取。
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。
Substitution 控制項或 VaryByCustom="userRole" 區分。OutputCache 僅快取 GET/HEAD,POST 會略過,但若 Action 同時支援 GET/POST 需注意。HttpResponse.RemoveOutputCacheItem("/Product.aspx") 或使用 SqlCacheDependency。web.config 設 debug="true" 會停用 OutputCache,部署時必須設 false。Performance Counter: ASP.NET Applications / Output Cache Hit Ratio善用 OutputCache 並配合合理的 VaryBy* 策略,能以最低成本獲得顯著效能提升;關鍵在於「精準識別可快取內容」與「建立可靠的失效機制」。