In earlier post we learned about how to use caching in asp.net mvc application.
Here we learn how to clear cache object in Asp.net MVC application, remove memory cache from server using C# code
Before we learn how to remove object from cache, we need to understand why do we need to remove?
Web application development is continuous process; we as application developer continuously keep making changes to make the application more efficient and user friendly, and to meet the business requirement that become necessary.
During that process, you may come across situation when you see after making changes in application when you are publishing and deploying on server, the updated files are not getting reflected or not showing the changes you have made.
Reason could be old cached object; here are some common ways to deal with the situation.
[OutputCache(Duration = 1060)] public ActionResult ManageStudents() { ViewBag.DataTime = DateTime.Now.Millisecond; //ViewBag.Data = _dto.GetStudents(); return View(); }
[OutputCache(Duration = 1200, VaryByParam = "StudentId", Location = OutputCacheLocation.Client)]Or
[OutputCache(Duration = 1200, VaryByParam = "StudentId", Location = OutputCacheLocation.Server)]
Now let's look how we can clear cache or remove cache item using code.
Removing current HttpContext cache object using keys.
List<string> keys = new List<string>(); // Collect all Cache Keys foreach (DictionaryEntry item in HttpContext.Current.Cache) { keys.Add(item.Key.ToString()); } // Remove all Cache Keys foreach (string key in keys) { HttpContext.Current.Cache.Remove(key); }
There is no clear method in memorycache object, we need to remove each item one by one.
MemoryCache cache = MemoryCache.Default; //long _itemCount = cache.GetCount(); List<string> cacheKeys = cache.Select(kvp => kvp.Key).ToList(); foreach (string cacheKey in cacheKeys) { cache.Remove(cacheKey); }
In asp.net framework, there are some provision to set cache expiry date for static content in web config file, we can set a specific date or we can set max age as cache expiry date for static, we to remove content from cache you can simply make changes in following tags in web.config file.
<system.webServer> <staticContent> <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00"/> <clientCache cacheControlMode="UseExpires" httpExpires="Tue, 19 Jan 2019 03:14:07 GMT"/> </staticContent> </system.webServer>
Note, you can keep only one of above clientCache tag, I have kept two just to show you how to set different values.