通過反編譯驗證:
// HttpContext.Cache 屬性實現
public Cache Cache { get { return HttpRuntime.Cache; } }
兩者返回的都是 HttpRuntime.Cache 靜態實例,應用程序域級單例。
| 場景 | HttpContext.Current.Cache | HttpRuntime.Cache |
|---|---|---|
| ASP.NET 請求管道內 | ✅ 可用 | ✅ 可用 |
| 非請求上下文(定時任務、後台線程、單元測試) | ❌ HttpContext.Current 為 null | ✅ 正常訪問 |
應用程序啟動階段 (Application_Start) | ❌ 未初始化 | ✅ 已就緒 |
| 類庫/服務層代碼 | ⚠️ 引入 System.Web 依賴 | ✅ 僅需 System.Web 引用 |
// 統一封裝緩存助手,屏蔽底層差異
public static class CacheHelper {
private static readonly Cache _cache = HttpRuntime.Cache;
public static T Get(string key) => (T)_cache[key];
public static void Set(string key, object value, TimeSpan sliding)
=> _cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, sliding);
public static void Remove(string key) => _cache.Remove(key);
}
原則:業務代碼依賴抽象 (CacheHelper),而非具體實現 (HttpRuntime.Cache)。