Clear Caching in Asp.net MVC

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

Why do we need to remove object from cache?

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.

  • Old pages are being fetched from your browser caches (like Google chrome, Firefox, internet explorer etc.)
  • You have explicitly set the output caching expiration date time in your action code like example below.
    [OutputCache(Duration = 1060)]
    public ActionResult ManageStudents()
    {
        ViewBag.DataTime = DateTime.Now.Millisecond;
        //ViewBag.Data = _dto.GetStudents();
        return View();
    }
  • Probably you have set the other additional parameters in your controller code like cache location client or server.
    [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.

Remove Cache from current HttpContext

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);
}
Remove Cache from MemoryCache

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);
}
Static Content Cache Control

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.


 
Remove Caching In ASP.NET MVC
Aspnet MVC Training
Asp.net MVC tutorials, learn model view controllers with c#, develop database driven web application using Asp.net MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial