我想構建一個MVC應用程序,用.NET Framework 4.0的緩存機制替換會話對象。使用MemoryCache的C#MVC替換會話
應用程序必須在某種緩存中存儲一些值以保持數據庫流量和加載時間較低(例如設置,下拉值等)。用戶使用用戶名和密碼驗證他們自己。這裏使用默認的FormsAuthentication。我的想法是爲每個用戶創建一個獨特的MemoryCache
,併爲應用程序創建一個通用的MemoryCache
。
我對用戶MemoryCache
吸氣看起來像這樣
private MemoryCache _memCache
{
get
{
if(HttpContext.Application[User.Identity.Name] == null)
{
HttpContext.Application[User.Identity.Name] = new MemoryCache(User.Identity.Name);
}
return HttpContext.Application[User.Identity.Name] as MemoryCache;
}
}
如果用戶退出的緩存將被佈置。
這是應用程序
private MemoryCache _appMemCache
{
get
{
if(HttpContext.Application["ApplicationMemoryCache"] == null)
{
HttpContext.Application["ApplicationMemoryCache"] = new MemoryCache("ApplicationMemoryCache");
}
return HttpContext.Application["ApplicationMemoryCache"] as MemoryCache;
}
}
的問題是,如果應用程序對象可用來存儲MemoryCache
全球MemoryCache
。如果CacheItemPolicy
沒有這個問題的工作。
我不使用會話的原因是可能的超時和阻塞並行請求。
請參閱[考慮使用會話狀態](https://brockallen.com/2012/04/07/think-twice-about-using-session-state/) - 它明確指出會話狀態不是存放用戶資料數據的地方。但我同意@ChrisPratt,你應該瞄準消除或最小化會話狀態的使用,而不是拿出精心設計的方法來取代它。 – NightOwl888