快取是提升 ASP.NET 應用程式效能的關鍵技術。本文系統整理五大快取層面:頁面輸出快取、部分頁面快取、資料源快取、Cache 物件快取與 SQL 快取相依性,並提供關鍵屬性、程式碼範例與最佳實務。
在 .aspx 頁面加入 @ OutputCache 指令即可快取整頁輸出。
<%@ OutputCache Duration="60" VaryByParam="*" Location="Server" %>
| 屬性 | 說明 |
|---|---|
Duration | 快取秒數(必填) |
VaryByParam | 依查詢字串/表單參數變化快取(必填,none 或 * 或參數名) |
VaryByControl | 用戶控件:依控制項 ID 變化快取 |
VaryByCustom | 自訂變化邏輯(如 browser 或覆寫 GetVaryByCustomString) |
VaryByHeader | 依 HTTP 標頭變化快取 |
Location | 快取位置:Any/Client/Server/None/Downstream/ServerAndClient |
NoStore | 防止敏感資料被 Proxy 快取 |
CacheProfile | 引用 web.config 中定義的快取設定檔 |
SqlDependency | 依資料庫資料變更使快取失效 |
Shared | 用戶控件輸出是否跨頁共享 |
// 建立檔案相依性
Response.AddFileDependency(Server.MapPath("test.xml"));
// 移除特定頁面快取
HttpResponse.RemoveOutputCacheItem(Page.ResolveUrl("~/test.aspx"));
// 使用鍵值相依性讓多頁同時失效
// 頁面載入時建立相依性
Cache.Insert("PageKey", DateTime.Now);
Response.AddCacheItemDependency("PageKey");
// 需要失效時
Cache.Remove("PageKey");
在 .ascx 加入 @ OutputCache,可設定 Shared="true" 跨頁共享。
<asp:Substitution runat="server" MethodName="GetFreshContent" />,方法必須為 static。Response.WriteSubstitution(callback),回呼可為實例或靜態方法,適合自訂控件。PartialCachingControl ctrl = (PartialCachingControl)Page.LoadControl("CachedControl.ascx");
ctrl.CachePolicy.SetExpires(DateTime.Now.AddSeconds(30));
PlaceHolder1.Controls.Add(ctrl);
SqlDataSource、ObjectDataSource、XmlDataSource 內建快取支援。
<asp:SqlDataSource ...
EnableCaching="true"
CacheDuration="60"
CacheExpirationPolicy="Absolute" />
<!-- Sliding 為滑動過期 -->
SelectCommand、SelectParameters、ConnectionString 視為相同快取鍵,自動共享。XmlDataSource 可設 DataFile 建立檔案相依性。CacheKeyDependency="MyKey"。Global.asax Application_Start 初始化:Cache.Insert("MyKey", DateTime.Now, null, DateTime.MaxValue, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);Cache.Remove("MyKey"); 或 Cache.Insert("MyKey", DateTime.Now); 觸發所有相依資料源重新載入。可快取任意物件:DataSet、DataTable、自訂類別、集合等。
DataTable dt = Cache["dtKey"] as DataTable;
if (dt == null)
{
dt = GetDataFromDB();
Cache.Insert("dtKey", dt, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
}
GridView1.DataSource = dt;
GridView1.DataBind();
Cache.Insert("key", value, dependency,
DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration,
CacheItemPriority.High, OnItemRemoved);
void OnItemRemoved(string key, object value, CacheItemRemovedReason reason) { ... }
ASP.NET 支援兩種模式:
pollTime)。aspnet_regsql -C "connStr" -ed -t TableName 啟用資料庫與資料表通知。web.config 設定 <sqlCacheDependency enabled="true" pollTime="1000">。Cache 使用 SqlDependency="DB:Table" 或 new SqlCacheDependency("DB", "Table")。ALTER DATABASE MyDB SET ENABLE_BROKER;授權 GRANT SUBSCRIBE QUERY NOTIFICATIONS TO [User]。SqlDependency.Start(connStr); 在 Application_Start;使用 new SqlCacheDependency(command) 或設定 SqlCacheDependency="CommandNotification"。