Clearing Page Cache in ASP.NET

Viewed 102815

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#?

8 Answers

I've found the answer I was looking for:

HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");

Using Response.AddCacheItemDependency to clear all outputcaches.

  public class Page : System.Web.UI.Page
  {
    protected override void OnLoad(EventArgs e)
    {
        try
        {
            string cacheKey = "cacheKey";
            object cache = HttpContext.Current.Cache[cacheKey];
            if (cache == null)
            {
              HttpContext.Current.Cache[cacheKey] = DateTime.UtcNow.ToString();
            }

            Response.AddCacheItemDependency(cacheKey);
        }
        catch (Exception ex)
        {
            throw new SystemException(ex.Message);
        }

        base.OnLoad(e);
    }     
 }



  // Clear All OutPutCache Method    

    public void ClearAllOutPutCache()
    {
        string cacheKey = "cacheKey";
        HttpContext.Cache.Remove(cacheKey);
    }

This is also can be used in ASP.NET MVC's OutputCachedPage.

Hmm. You can specify a VaryByCustom attribute on the OutputCache item. The value of this is passed as a parameter to the GetVaryByCustomString method that you can implement in global.asax. The value returned by this method is used as an index into the cached items - if you return the number of comments on the page, for instance, each time a comment is added a new page will be cached.

The caveat to this is that this does not actually clear the cache. If a blog entry gets heavy comment usage, your cache could explode in size with this method.

Alternatively, you could implement the non-changeable bits of the page (the navigation, ads, the actual blog entry) as user controls and implement partial page caching on each of those user controls.

If you change "*" to just the parameters the cache should vary on (PostID?) you can do something like this:

//add dependency
string key = "post.aspx?id=" + PostID.ToString();
Cache[key] = new object();
Response.AddCacheItemDependency(key);

and when someone adds a comment...

Cache.Remove(key);

I guess this would work even with VaryByParam *, since all requests would be tied to the same cache dependency.

why not use the sqlcachedependency on the posts table?

sqlcachedependency msdn

This way your not implementing custom cache clearing code and simply refreshing the cache as the content changes in the db?

HttpRuntime.Close() .. I try all method and this is the only that work for me

Related