Remove ASP.NET Page Output Cache Entries
page 1 of 1
Published: 02 May 2005
Unedited - Community Contributed
Abstract
This article discusses two techniques for programmatically invalidating the cache of ASP.NET pages that use Output Caching, allowing control over cache expiration from code.
by Steven Smith
Feedback
Average Rating: 
Views (Total / Last 10 Days): 45482/ 62

[ Sample Code ]

Programmatic Output Cache Entry Removal

Introduction

A frequently asked question I get when I present or write about ASP.NET’s caching features is, “How do I programmatically remove a page from the output cache?”  For a long time now I’ve been unsure of the answer to this.  I finally broke down and learned that yes, you can do this, and discovered two methods for implementing the solution.  Download this article’s sample code and you’ll quickly see how each method works -- the code required is minimal.

Remove One Page from the Cache

The first technique is simply to specify a particular page and have its output cache entry removed. This is accomplished using the HttpResponse.RemoveOutputCacheItem(string path) method. The path expected is an “absolute virtual path” which means it must be of the form “/foldername/pagename.aspx”. From the sample code, you could create a button that, when pressed, removes the cache entry for a particular page.  The code in Listing 1 shows how this would be implemented.

Listing 1: Remove Output Cache for One Page

private void RemoveButton_Click(object sender, System.EventArgs e)
{
    HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");
}

This works provided that there is a page named CacheForever.aspx in the folder /caching.  On that page, you would implement output caching by using the <%@ OutputCache %> directive as usual -- nothing special needs to be done to the cached page for this technique to work.

Remove Many Pages from the Cache

Another technique involves linking many pages together through the use of a key-based cache dependency.  This technique requires a little bit more code, but is still very simple to implement.  The simple implementation provided with the sample code download took three lines of code.  The most important one is added to the page (every page) that is output cached. Listing 2 shows how the cache dependency is added to the page in its Page_Load event handler.

Listing 2: Add Key Dependency to Page

private void Page_Load(object sender, System.EventArgs e)
{
      Response.AddCacheItemDependency("Pages");
}

At this point, the page depends on the cache key “Pages”.  In a real application, you would want this string value to be read from a configuration file, since it will be used in several places and it’s bad practice to use a string literal in more than one place if at all avoidable.  If you test out your page after adding this, and before you do anything else, you’ll find that it has disabled your output caching. The reason for this is that a cache key dependency automatically fails if the key does not exist in the cache. At this point, we haven’t done anything to insert an item into the cache with a key of “Pages”.  That’s the next step.  Listing 3 shows how to add such a key in Application_Start so that we can be sure it is always present.

Listing 3: Configure Global.asax to Create Key

protected void Application_Start(Object sender, EventArgs e)
{
      HttpContext.Current.Cache.Insert("Pages", DateTime.Now, null,
            System.DateTime.MaxValue, System.TimeSpan.Zero,
            System.Web.Caching.CacheItemPriority.NotRemovable,
            null);
}

Finally, to refresh all pages that depend on this key, we simply need to do this exact same thing inside another page or control. For instance, you might create a button called “Expire Page Cache” in your website’s admin menu. Listing 4 shows what that button’s click event handler would look like.

Listing 4: Button Click Handler to Expire Output Cache Pages

private void RemoveKeyButton_Click(object sender, System.EventArgs e)
{
      HttpContext.Current.Cache.Insert("Pages", DateTime.Now, null,
            System.DateTime.MaxValue, System.TimeSpan.Zero,
            System.Web.Caching.CacheItemPriority.NotRemovable,
            null);
}

Summary

I’d like to thank Scott Mitchell for his blog entry that I found when I Googled for this. He led me to find the first method. I’d also like to thank G. Andrew Duthie, who suggested the second method in a private mailing list.

Resources



User Comments

Title: Limitation   
Name: Rohit
Date: 2010-05-22 3:38:15 AM
Comment:
Any of the above codes doesnt clear the cache ,, so if you dont know dont suggest people
Title: Limitations of ASP.NET Cache   
Name: Tom
Date: 2010-03-29 6:31:19 AM
Comment:
Hi Steven,

Great Stuff!! i'll appreciate if you write something about the limitations of ASP.NET Cache as well. i recently read an article according to which its is not a good idea to use ASP.NET cache for larger web farms as it's In-proc and standalone nature can ends up giving some serious scalability issues. i am also sharing a link below which also talks about the same issue.

http://www.alachisoft.com/ncache/asp-net-cache.html
Title: How to clea Out put chtche   
Name: Mohan Krishna
Date: 2009-06-06 1:43:26 AM
Comment:
i have used out put catche as

<%@ OutputCache Duration="100" Location="Any" VaryByParam="none" %> in the sample.aspx page.

i want to clear the output catche by clicking the home or some other button

while getting onceagain into the same it is showing the previous stage data only.

please any one can give solution for me...

By
Mohan Krishna
Title: pls help   
Name: Neha
Date: 2008-11-21 12:12:41 AM
Comment:
I hav Used this:
Dim szCookieHeader As String = System.Web.HttpContext.Current.Request.Headers("Cookie")

If Not IsNothing(szCookieHeader) AndAlso szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0 Then
Dim AppNom As String
Try
AppNom = Request.ApplicationPath.Substring(Request.ApplicationPath.LastIndexOf("/") + 1)
Catch ex As Exception
AppNom = "?Inconnue?"
End Try

Response.Redirect("/Sil_1_2/login.aspx?AppURL=" & Request.ApplicationPath & "&AppNom=" & AppNom)
End If

bt it's nt wrkng properly.if i m using dat page on address bar den it's opening.i want it should nt open again.
Title: hiiiiiiiiii   
Name: richa
Date: 2008-11-21 12:06:56 AM
Comment:
how we expire the page.and it should not be open more than once.
Title: Mr.   
Name: Josh
Date: 2008-05-02 9:29:38 AM
Comment:
I really didn't get why I need to put key based dependency to remove or expire a page. What about if I implement a custom http module (derived from IHttpModule) which can store my ASP.NET pages directly to cache with some page expirations. This module should be able to read all the page settings from Web.Config so that I don't have to specify these settings on every page.

I pasted the example here but I think this feedback box does not support escape characters and it says that some error has occured and that is sent to the team.
Title: For user controls   
Name: Teemu
Date: 2007-11-04 11:01:38 AM
Comment:
See my blog post

ASP.NET: clear user control output cache
http://aspadvice.com/blogs/joteke/archive/2007/10/31/ASP.NET_3A00_-clear-user-control-output-cache.aspx
Title: Nope?   
Name: Owen
Date: 2007-10-30 4:55:01 PM
Comment:
I tried putting the CacheItemDependency in, but it did not work: the user-control still does not re-cache....
Title: Nope   
Name: Steve Smith
Date: 2007-09-18 3:05:35 PM
Comment:
@Owen: You need to expire the Page the UserControl is on. This is lame because probably that is many pages. The other (better) option is to use the Response.AddCacheItemDependency() which I think should work with a user control though I haven't tested it yet. Then just expire/update whatever it's depending on.
Title: User controls?   
Name: Owen
Date: 2007-09-18 2:57:53 PM
Comment:
So, how do I expire the output cache on a user control that's loaded programmatically. The following code does not work:

httpcontext.current.response.RemoveOutputCacheItem("/Controls/UserControl.ascx")

I don't get an error, but the control does not re-load: I get the cached version....
Title: Other way to remove the page from cache   
Name: Amit
Date: 2006-06-25 2:06:23 PM
Comment:
Response.CacheControl = "no-cache"
Response.Expires = -1
Title: Mr.   
Name: Hammam A. Ahmed
Date: 2006-05-29 12:32:19 AM
Comment:
Thanks Alot for this information realy appreciate
Title: Question   
Name: Andy
Date: 2006-03-05 10:18:02 AM
Comment:
This idea makes sense, but after I execute my RemoveKeyButton_Click method I get this:
1. Page and control cache is expired.
2. Pages are still served from cache until I hit the F5 key.
3. Only after running your code I'm able to bring a fresh page with the F5 key. (I'm using IE 6)
Title: remove cahing   
Name: Arpi
Date: 2006-02-13 8:45:14 AM
Comment:
Many many thanks for that topic
Title: thanks, but...   
Name: Omar AA
Date: 2005-11-23 3:53:40 AM
Comment:
thanks for the article, but i'd like to know how i can disable caching for the whole page, i got a page that reads from an xml file to a dataset and the dataset is bound to a repeater, i want the data to be as close to real time as possible, how can i accomplish this?
Title: Thanks   
Name: EV
Date: 2005-10-02 7:45:56 AM
Comment:
Thanks man
i have been looked for solution for a long time
Title: very Good   
Name: Me And Hasan
Date: 2005-06-27 8:54:19 AM
Comment:
it was very good article.
thank you very boos.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-10-04 4:03:39 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search