HttpContext.Current.Cache item null after page refresh

前端 未结 2 531
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-05 17:52

I\'ve a C# web page in which I\'m storing a List<> object in the server cache, using HttpContext.Current.Cache. The object is saved in the cache after the first page load

2条回答
  •  孤独总比滥情好
    2021-01-05 18:17

    Can you use the System.Runtime.Caching instead. That way you're not dependent on the HttpRuntime namespace.

    I suspect you're getting null because .Net is clearing it due to web-server restarts. Would it be better to do something along the lines of

        public List GetUsers()
        {
            var cache = System.Runtime.Caching.MemoryCache.Default;
            if (cache["MainADList"] == null)
            {
                // Rebuild cache. Perhaps for Multithreading, you can do object locking
                var cachePolicy = new System.Runtime.Caching.CacheItemPolicy() { AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(30) };
                var users = Uf.GetUsers();
                cache.Add(new System.Runtime.Caching.CacheItem("MainADList", users), cachePolicy);
    
                return users;
            }
    
            return cache["MainADList"] as List; 
        }
    

提交回复
热议问题