Programmatically removing a page from ASP.NET’s output cache

So here’s an interesting thing I thought I should mention. In working on some of the code for this blog engine, I’ve been using the ASP.NET OutputCache directive on some of the .aspx pages to help speed things up. This way, in the event of a slashdotting, or some other sudden increase in traffic, you’re not rebuilding the page or hitting the DB for each request. Nice, huh?

So that’s all fine and good, but what about when you want to blow the page out of the cache? Case in point, in adding comments to the blog engine, the user will expect to see the comment posted immediately, not in 3 minutes.

Sure, I could go in and just make sections of the page cacheable, but… eh… that’s a lot of work. I want to be lazy and just blow the cache away. Sounds simple enough, right? But, for the life of me, I just could not get it to work.

After doing some googleing on the topic, playing around with both the Cache.Remove() as well as the HttpResponse.RemoveOutputCacheItem() methods just seemed to not work.

After several hours of pulling my hair out, I realized the mistake was in the OutputCache directive on the page. I had been using:

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

What I was missing, was adding the Location parameter to the statement. By changing it to

<%@ OutputCache Duration=“60” VaryByParam =”*” Location=“Server” %>

the HttpResponse.RemoveOutputCacheItem() method would now work. Woo-hoo!

The other trick I found was when calling the HttpResponse.RemoveOutputCacheItem() method, for the path parameter should be the full virtual path to the page. So, for some site: http://foo.com/somedir/somepage.aspx the path param would be “/somedir/somepage.aspx”. Also, it shoud not include any QueryString information.

Dec 1, 2005

9:38 pm

This entry has been tagged with:

Technologyasp