William Duffy

Glasgow Based C# ASP.NET Web Developer

Clearing ASP.NET Cache

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.");

Tagged as , , + Categorized as ASP.NET, C#


  1. Agreed. We did something similar that was hidden in our CMS. Totally the most useful button ever! “Why isn’t that working….?” Click “Sorry I must be mistaken”. 1 button saves the day!

Leave a Reply