Clearing Page Cache in ASP.NET


Question

For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...

<%@OutputCache Duration="600" VaryByParam="*" %>

However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.

How do I do this in ASP.Net C#?

1
50
6/1/2010 5:55:58 AM

Accepted Answer

I've found the answer I was looking for:

HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");
48
8/14/2008 8:04:36 PM

The above are fine if you know what pages you want to clear the cache for. In my instance (ASP.NET MVC) I referenced the same data from all over. Therefore, when I did a [save] I wanted to clear cache site wide. This is what worked for me: http://aspalliance.com/668

This is done in the context of an OnActionExecuting filter. It could just as easily be done by overriding OnActionExecuting in a BaseController or something.

HttpContextBase httpContext = filterContext.HttpContext;
httpContext.Response.AddCacheItemDependency("Pages");

Setup:

protected void Application_Start()
{
    HttpRuntime.Cache.Insert("Pages", DateTime.Now);
}

Minor Tweak: I have a helper which adds "flash messages" (Error messages, success messages - "This item has been successfully saved", etc). In order to avoid the flash message from showing up on every subsequent GET, I had to invalidate after writing the flash message.

Clearing Cache:

HttpRuntime.Cache.Insert("Pages", DateTime.Now);

Hope this helps.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon