@ OutputCache 指令可快取整頁或使用者控制項(.ascx)輸出 HTML,大幅降低伺服器負載。但後台管理常需「立即生效」更新內容,必須手動移除快取。
<%@ OutputCache Duration="60" VaryByParam="none" %>
移除方式:
HttpResponse.RemoveOutputCacheItem(Page.ResolveUrl("~/Default.aspx"));
需使用ResolveUrl取得相對虛擬路徑(含~),否則找不到快取鍵值。
共享快取的控制項無法直接用 RemoveOutputCacheItem 移除,需引入 VaryByCustom 機制。
<%@ OutputCache Duration="60" VaryByParam="none" Shared="true" VaryByCustom="CacheGroupClass" %>
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (arg == "CacheGroupClass")
{
var cache = HttpRuntime.Cache;
object flag = cache["CacheGroupClass"];
if (flag == null)
{
flag = DateTime.Now.Ticks.ToString(); // 初始化版本戳記
cache.Insert("CacheGroupClass", flag);
}
return flag.ToString(); // 回傳目前版本戳記
}
return base.GetVaryByCustomString(context, arg);
}
var cache = HttpRuntime.Cache;
if (cache["CacheGroupClass"] != null)
cache.Remove("CacheGroupClass"); // 移除版本戳記,強制下次請求重新產生
VaryByCustom 回傳的字串會成為快取鍵值一部分。移除 Cache["CacheGroupClass"] 後,下一次請求 GetVaryByCustomString 會產生新的 Ticks 字串,導致快取鍵值改變,ASP.NET 視為新快取項目而重新渲染控制項。
public static class CacheHelper
{
public static void Set(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
HttpRuntime.Cache.Insert(key, value, null, absoluteExpiration, slidingExpiration);
}
public static T Get<T>(string key) => HttpRuntime.Cache[key] as T;
public static void Remove(string key) => HttpRuntime.Cache.Remove(key);
}
頁面快取移除直觀簡單;控制項共享快取則需透過 VaryByCustom + HttpRuntime.Cache 版本戳記間接達成。掌握此模式,即可在保有快取效能與資料即時性之間取得平衡。