Clearing ASP.NET Cache

Posted by William on Apr 12, 2011

ASP.NET’s caching system is invaluable for speeding up your website and reducing your server/database load. However, sometimes you will find a need to manually clear the cache and allow it to rebuild with fresh data. As simple as this seems it can prove trickier than you would expect.

The following code snippet allows you to do just this. Simply create a generic handler somewhere accessible on your website to call when you need to clear the cache. For example www.yoursite.com/clearcache.ashx.

using System;
using System.Web;
using System.Collections;
 
public class ClearCache : IHttpHandler
{
    public bool IsReusable
    {
        get { return true; }
    }
 
    public void ProcessRequest(HttpContext context)
    {
        foreach (DictionaryEntry item in context.Cache)
            context.Cache.Remove(item.Key as string);
 
        context.Response.ContentType = "text/html";
        context.Response.Write("Cache cleared.");
    }
}