ASP.NET Clear Cache

13,920

Solution 1

is it possible to Clear a certain page from the Cache?

Yes:

HttpResponse.RemoveOutputCacheItem("/pages/default.aspx");

You can also use Cache dependencies to remove pages from the Cache:

this.Response.AddCacheItemDependency("key");

After making that call, if you modify Cache["key"], it will cause the page to be removed from the Cache.

In case it might help, I cover caching in detail in my book: Ultra-Fast ASP.NET.

Solution 2

more simple one...

public static void ClearCache()
{
    Cache cache = HttpRuntime.Cache;

    IDictionaryEnumerator dictionaryEnumerators = cache.GetEnumerator();

    foreach (string key in (IEnumerable<string>) dictionaryEnumerators.Key)
    {
        cache.Remove(key);
    }

}

Solution 3

The following code will remove all keys from the cache:

public void ClearApplicationCache(){
    List<string> keys = new List<string>();
    // retrieve application Cache enumerator
    IDictionaryEnumerator enumerator = Cache.GetEnumerator();
    // copy all keys that currently exist in Cache
    while (enumerator.MoveNext()){
        keys.Add(enumerator.Key.ToString());
    }
    // delete every key from cache
    for (int i = 0; i < keys.Count; i++) {
        Cache.Remove(keys[i]);
    }
}

Modifying the second loop to check the value of the key before removing it should be trivial.

Hope this helps.

Share:
13,920
Lieven Cardoen
Author by

Lieven Cardoen

Minds to blow, places to go...

Updated on June 04, 2022

Comments

  • Lieven Cardoen
    Lieven Cardoen almost 2 years

    If you cache pages in a HttpHandler with

    _context.Response.Cache.SetCacheability(HttpCacheability.Public);
    _context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(180));
    

    is it possible to clear a certain page from the cache?