快取是提升 Web 應用效能、降低資料庫壓力、改善使用者體驗的「銀彈」。ASP.NET 提供兩大快取層級:輸出快取 (頁面/片段級) 與 資料快取 (物件級),靈活組合可構建多層次快取策略。

將最終渲染的 HTML 直接儲存在記憶體,後續相同請求繞過完整頁面生命週期直接回應,效能提升極大。
<%@ OutputCache Duration="60" VaryByParam="None" %>
Duration:快取秒數 (此例 60 秒)。VaryByParam:依查詢字串/表單參數變化建立不同快取版本,None 表示忽略參數 (所有使用者共用同一快取);* 表示任意參數不同即建立新版本;"id;category" 指定參數名。| 屬性 | 用途 | 範例 |
|---|---|---|
| VaryByControl | 依使用者控制項內控制項屬性值變化 | VaryByControl="ddlCategory" |
| VaryByCustom | 自訂變異邏輯 (需覆寫 Global.asax GetVaryByCustomString) | VaryByCustom="browser" (依瀏覽器型別) |
| VaryByHeader | 依 HTTP Header 變化 (如 Accept-Language) | VaryByHeader="Accept-Language" |
| Location | 快取位置 | Any/Client/Downstream/Server/None/ServerAndClient |
| NoStore | 防止敏感資料被 Proxy/瀏覽器快取 | NoStore="true" |
| SqlDependency | SQL 快取相依性 (資料異動自動失效) | SqlDependency="CommandNotification" |
<%@ OutputCache Duration="120" VaryByParam="CategoryID" Shared="true" %>
Shared="true" 讓多頁面引用同一控制項時共用快取實例,節省記憶體。
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" %>
<%@ OutputCache Duration="20" VaryByParam="None" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div class="title">Output Cache Demo</div>
Date: <asp:Label ID="lblDate" runat="server" />
Time: <asp:Label ID="lblTime" runat="server" />
</asp:Content>
protected void Page_Load(object sender, EventArgs e)
{
lblDate.Text = DateTime.Now.ToShortDateString();
lblTime.Text = DateTime.Now.ToLongTimeString();
}
首次載入顯示真實時間,20 秒內重新整理頁面時間不變,證明快取生效。
透過 System.Web.Caching.Cache 類別 (可用 HttpContext.Current.Cache 或 Page.Cache 存取) 存放資料集、實體集合、計算結果等任意可序列化物件。
Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback):完整控制過期策略、相依性、移除通知。Add:鍵存在時不覆蓋,返回舊值。Get(key) / 索引器 [key]:讀取,需檢查 null。Remove(key):手動移除。DateTime.Now.AddMinutes(10) — 固定時間點失效。TimeSpan.FromMinutes(5) — 多久未存取即失效,適合熱點資料。CacheDependency (檔案/目錄/快取鍵)、SqlCacheDependency (資料表變更)、AggregateCacheDependency (多重相依 OR 邏輯)、自訂 ICacheDependency。public List GetHotProducts()
{
const string key = "HotProducts";
var products = Cache[key] as List;
if (products == null)
{
lock (key) // 雙重檢查鎖定,防止快取失效瞬間大量請求穿透 DB
{
products = Cache[key] as List;
if (products == null)
{
products = ProductRepository.GetHotProducts(); // 昂貴查詢
Cache.Insert(key, products, null,
DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration,
CacheItemPriority.High, null);
}
}
}
return products;
}
ASP.NET Applications\Cache Total Entries、Cache API Hit Ratio,配合 CacheItemPriority 引導淘汰順序。Cache → AppFabric / Redis / Memcached,介面隔離 (IDistributedCache) 便於無縫遷移。輸出快取解決「頁面渲染重複運算」,資料快取解決「資料存取重複 I/O」。兩者疊加,配合合理的相依性與過期策略,可將典型 Web 應用回應時間壓縮 50%~90%,是高併發架構不可或缺的基石。