back to Jitbit Blog home About this blog

Clear/Flush all OutputCache in ASP.NET

by Alex Yumashev · Updated Apr 21 2021

If you're using OutputCache directive like this:

[OutputCache(Duration = 600, VaryByParam = "*", Location = OutputCacheLocation.Server)]

Or storing custom data in HttpRuntime.Cache like this

HttpRuntime.Cache.Add(...)

You probably caught yourself wondering

How can I flush/remove everything saved in my cache?

Some people recommend iterating through the items in HttpRuntime.Cache but this will only give you the custom items you stored, not the pages.

I've spent some time lurking through ASP.NET reference source and finally came up with a working solution.

public static void ClearAllCache()
{
    var runtimeType = typeof(System.Web.Caching.Cache);
    
    var ci = runtimeType.GetProperty(
       "InternalCache",
       BindingFlags.Instance | BindingFlags.NonPublic);
    
    var cache = ci.GetValue(HttpRuntime.Cache) as System.Web.Caching.CacheStoreProvider;
    var enumerator = cache.GetEnumerator();
    List<string> keys = new List<string>();
    while (enumerator.MoveNext())
    {
        keys.Add(enumerator.Key.ToString());
    }
    foreach (string key in keys)
    {
        cache.Remove(key);
    }
}

The code uses reflection to get to the "InternalCache" property, then cast it to CacheStoreProvider and then iterate through the keys there. Once you have the list of keys, simply remove them one by one.