Updated Sep 10 2019 :: by Alex Yumashev

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;
    enumerator = cache.GetEnumerator();
    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.


'Clear/Flush all OutputCache in ASP.NET' was written by Alex Yumashev
Alex Yumashev
Alex has founded Jitbit in 2005 and is a software engineer passionate about customer support. Alex holds a degree in computer science is a Microsoft Certified Solution Developer


Subscribe comments