views:

283

answers:

2

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?

A: 

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.

Mick Walker
Is this the same as you would use HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx"); "/caching/CacheForever.aspx" being one of the keys of Cache?
Lieven Cardoen
It is indeed - I honestly cannot think of any advantages my method has over calling HttpResponse.RemoveOutputCacheItem(); I just took the snippet from some production code I have here, so I know it works correctly.
Mick Walker
I assume this only affects caching on the server side and not client side?
Lieven Cardoen
-1 This will fail when Kernel Caching is configured in IIS
Josef
+1  A: 

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.

RickNZ
I assume this only affects caching on the server side and not client side. If you have set caching on client side for 180 seconds, then removing it from the server cache will not affect the client browser? (I know it's a stupid question but I want to be 100% sure). thx.
Lieven Cardoen
Correct. You can't programmatically remove an object from a client-side or proxy-based cache using server-side code. In addition, removing a page from the cache in one server or AppPool won't remove it from the cache in another server or AppPool.
RickNZ