Clearing Page Cache in ASP.NET
Asked Answered
P

9

53

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

Parody answered 14/8, 2008 at 19:39 Comment(0)
P
49

I've found the answer I was looking for:

HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");
Parody answered 14/8, 2008 at 20:4 Comment(5)
does anyone know if something like this is available for classic ASP?Inhospitality
I don't think caching was available in ASP, so no sorry.Parody
This clears all the caches for every for every params for that page.Bacchic
I'm using MVC 5.2.3, where should I write this code?Orna
I am using a web user control for dynamic menus, I am using outputcache and want to remove cache on logout, I used your solution and passed my user control's path but didn't work for me.Mourning
H
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.

Hartal answered 20/5, 2010 at 18:24 Comment(6)
Ir works only for entire page caching. It doesn't work for child actions. Any suggestions?Jakejakes
and.maz did you figure this out?Scintillation
@and.maz In case you figured out how to do this for child actions, there's a bounty here.Uta
This did not work for me. This inability to clear elements of a cache seem like one enormous shortcoming in mvcPent
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). dotnet.dzone.com/articles/programmatically-clearing-0Janettejaneva
@Hartal can you explain how to clear all cached pages of website after logoutScarron
C
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.

Cubital answered 6/1, 2009 at 13:55 Comment(1)
Perfect, that's what I'm looking for. There is only one thing you should change. HttpContext.Current.Cache.Remove(cacheKey);Bacchic
H
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();
Huppert answered 22/6, 2011 at 12:24 Comment(0)
I
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.

Ichthyosis answered 14/8, 2008 at 19:51 Comment(0)
O
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.

Oliana answered 14/8, 2008 at 19:55 Comment(0)
B
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?

Blossom answered 2/1, 2010 at 0:17 Comment(0)
B
0

First off, make sure you've set up our caching properly. You've got the right idea with the OutputCache directive in your ASPX file. This line:

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

tells ASP.NET to cache the page for 10 minutes (600 seconds), but it'll vary the cache based on different parameters, ensuring each version of the page is stored separately in the cache.

Now, when a new comment is posted, you need to bust that cache so the page refreshes and everyone can see the latest comment. To do this, we'll use a bit of C# code in your code-behind file (probably something like YourPageName.aspx.cs).

Inside your code-behind, you'll need to call the HttpResponse.RemoveOutputCacheItem method to clear the cache for the specific page. You'll want to call this method whenever a new comment is posted.

Here's a basic example of how you might do it:

protected void PostCommentButton_Click(object sender, EventArgs e)
{
    // Code to save the comment to the database goes here...

    // Now, let's clear the cache for the current page
    string pageUrl = HttpContext.Current.Request.Url.AbsolutePath;
    HttpResponse.RemoveOutputCacheItem(pageUrl);
}

In this code snippet, PostCommentButton_Click is the event handler for when someone submits a new comment. After saving the comment to your database (you'll need to add that part), we get the current page's URL using HttpContext.Current.Request.Url.AbsolutePath. Then, we call HttpResponse.RemoveOutputCacheItem with the page URL to clear the cache for that specific page.

Bursar answered 23/4 at 10:22 Comment(0)
S
-1

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

Stingo answered 18/1, 2011 at 18:55 Comment(1)
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.Parody

© 2022 - 2024 — McMap. All rights reserved.