52

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

Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
GateKiller
  • 74,180
  • 73
  • 171
  • 204

8 Answers8

49

I've found the answer I was looking for:

HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");
GateKiller
  • 74,180
  • 73
  • 171
  • 204
41

The above are fine if you know what pages you want to clear the cache for. In my instance (ASP.NET MVC) I referenced the same data from all over. Therefore, when I did a [save] I wanted to clear cache site wide. This is what worked for me: http://aspalliance.com/668

This is done in the context of an OnActionExecuting filter. It could just as easily be done by overriding OnActionExecuting in a BaseController or something.

HttpContextBase httpContext = filterContext.HttpContext;
httpContext.Response.AddCacheItemDependency("Pages");

Setup:

protected void Application_Start()
{
    HttpRuntime.Cache.Insert("Pages", DateTime.Now);
}

Minor Tweak: I have a helper which adds "flash messages" (Error messages, success messages - "This item has been successfully saved", etc). In order to avoid the flash message from showing up on every subsequent GET, I had to invalidate after writing the flash message.

Clearing Cache:

HttpRuntime.Cache.Insert("Pages", DateTime.Now);

Hope this helps.

Kevin
  • 1,723
  • 2
  • 17
  • 16
  • 4
    Ir works only for entire page caching. It doesn't work for child actions. Any suggestions? – Andrei M Aug 19 '11 at 06:40
  • 3
    and.maz did you figure this out? – bobek Dec 06 '12 at 16:08
  • @and.maz In case you figured out how to do this for child actions, there's a bounty [here](http://stackoverflow.com/q/5126751/63733). – marapet Mar 25 '13 at 16:33
  • This did not work for me. This inability to clear elements of a cache seem like one enormous shortcoming in mvc – Dave Lawrence Jun 25 '13 at 15:43
  • Probably, you can't clear the cache because you use @Html.Action() to render the partial view. You will have to use `OutputCacheAttribute.ChildActionCache = new MemoryCache("NewRandomStringNameToClearTheCache");` to clear the entire "child action cache" (for all child actions - It seems there is no better approach without using a library). http://dotnet.dzone.com/articles/programmatically-clearing-0 – user2173353 Dec 10 '13 at 16:46
  • @Kevin can you explain how to clear all cached pages of website after logout – Mohit Shah Mar 04 '16 at 05:32
6

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.

  • Perfect, that's what I'm looking for. There is only one thing you should change. HttpContext.Current.Cache.Remove(cacheKey); – Sam Salim Nov 26 '15 at 10:58
3

On the master page load event, please write the following:

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();

and in the logout button click:

Session.Abandon();
Session.Clear();
DarthJDG
  • 16,511
  • 11
  • 49
  • 56
Mohd Adil
  • 31
  • 1
1

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.

John Christensen
  • 5,020
  • 1
  • 28
  • 26
1

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.

palmsey
  • 5,812
  • 3
  • 37
  • 41
1

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?

Brian Scott
  • 9,221
  • 6
  • 47
  • 68
-1

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

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Julien
  • 121
  • 13
  • 7
    I would suspect that this is closing the ASP.NET application process on IIS. This seems a bit excessive, would probably clear all caches and would have significant performance problems on large websites. – GateKiller Feb 11 '11 at 12:24