Lieven Cardoen
Lieven Cardoen

Reputation: 25969

ASP.NET Clear Cache

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?

Upvotes: 2

Views: 14195

Answers (3)

RickNZ
RickNZ

Reputation: 18652

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.

Upvotes: 5

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);
    }

}

Upvotes: 4

Mick Walker
Mick Walker

Reputation: 3847

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.

Upvotes: 2

Related Questions