頁面輸出快取將完整渲染後的 HTML 存放於伺服器記憶體,後續請求直接輸出快取內容,跳過頁面生命週期(Init、Load、Render 等),大幅降低 CPU 與資料庫壓力。適合低頻更新、高頻讀取的頁面(如首頁、產品列表、新聞詳情)。
<%@ OutputCache Duration="60" VaryByParam="none" %>
| 屬性 | 必要 | 說明 | 範例值 |
|---|---|---|---|
| Duration | 是 | 快取秒數 | 60, 300, 3600 |
| VaryByParam | 是 | 依查詢字串/表單參數變化快取,* 表示全部參數 | "id", "category;page", "*", "none" |
| VaryByControl | 否 | 依控件屬性值變化快取(如 DropDownList 選項) | "ddlCategory", "txtSearch" |
| VaryByCustom | 否 | 自定義快取變化邏輯(需在 Global.asax 覆寫 GetVaryByCustomString) | "browser", "userRole", "theme" |
| VaryByHeader | 否 | 依 HTTP 標頭變化快取 | "Accept-Language", "User-Agent" |
| Location | 否 | 快取位置:Any/Client/Server/Downstream/None | "Server" (預設) |
| NoStore | 否 | true:不儲存任何快取(含用戶端),用於敏感頁面 | "true"/"false" |
| CacheProfile | 否 | 引用 Web.config 定義的快取設定檔 | "LongTerm", "ShortTerm" |
| SqlDependency | 否 | SQL 快取相依性(資料變更自動失效) | "CommandNotification" |
<configuration>
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<!-- 長期快取:靜態內容、首頁 -->
<add name="LongTerm" duration="3600" varyByParam="none" location="Server" />
<!-- 短期快取:列表頁、搜尋結果 -->
<add name="ShortTerm" duration="300" varyByParam="page;size;keyword" location="Server" />
<!-- 使用者個人化:依用戶角色/語言變化 -->
<add name="Personalized" duration="600" varyByCustom="userRole;lang" location="Server" />
<!-- 無快取:敏感頁面、即時數據 -->
<add name="NoCache" duration="0" varyByParam="none" noStore="true" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
</configuration>
<%@ OutputCache CacheProfile="ShortTerm" %>
<%@ OutputCache Duration="300" VaryByParam="page;categoryId" %>
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="true" />
<%@ OutputCache Duration="600" VaryByControl="ddlCategory" %>
// Global.asax
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if (custom == "userRole")
{
return context.User.IsInRole("Admin") ? "Admin" : "User";
}
return base.GetVaryByCustomString(context, custom);
}
<%@ OutputCache Duration="600" VaryByCustom="userRole" %>
<%@ OutputCache Duration="3600" SqlDependency="CommandNotification" %>
// 需在 Web.config 啟用 sqlCacheDependency
// 並在 Global.asax Application_Start 啟用:SqlCacheDependencyAdmin.EnableNotifications(connStr)
// 以及啟用資料表:SqlCacheDependencyAdmin.EnableTableForNotifications(connStr, "Products")
// 在 Page_Load 中動態控制
protected void Page_Load(object sender, EventArgs e)
{
// 完全禁用快取(敏感頁面)
Response.Cache.SetNoStore();
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
// 或動態設定快取參數
Response.Cache.SetExpires(DateTime.Now.AddMinutes(10));
Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
Response.Cache.VaryByParams["categoryId"] = true;
}
ASP.NET Applications\Cache Total Entries、Cache Total Hit Ratio、Cache Total Turnover Rate| 陷阱 | 後果 | 解決 |
|---|---|---|
| VaryByParam="*" 濫用 | 每個查詢參數組合產生獨立快取,記憶體爆炸 | 明確列出必要參數 |
| 快取使用者個人化頁面 | 用戶 A 看到用戶 B 的資料 | VaryByCustom="userId" 或改用資料快取 |
| Duration 設太長 | 資料更新不及時反映 | 配合 SqlDependency 或主動失效 |
| Location="Client" 用於認證頁 | 瀏覽器快取敏感資訊 | NoStore="true" + Location="None" |
| UpdatePanel 內使用 OutputCache | 部分頁面快取失效/衝突 | 避免混用,改用資料層快取 |
OutputCache 是 ASP.NET 最簡單且效果立竿見影的效能優化手段。關鍵在於精準控制快取變化維度(VaryBy* 系列)與建立失效機制(SqlDependency/主動移除)。現代架構中,配合響應式快取策略(短快取+非同步刷新),可在用戶體驗與資料新鮮度間取得最佳平衡。