ttkalec
ttkalec

Reputation: 741

Invalidating OutputCache programmatically on UserControl

Is there any way of invalidating OutputCache on UserControl?
I've setup a partial caching on my site using UserControls and it's working fine.
I've set output cache like this in my user control:

<%@ OutputCache Duration="3600" VaryByParam="None" %>

My user contrlol is located in /UserControls/SomeAction.ascx
So I've tried to invalidate it using this and it didn't work.:

HttpResponse.RemoveOutputCacheItem("/UserControls/SomeAction.ascx");

I also tried this approach:
I've set HttpContext.Current.Cache.Insert("MyCache",DateTime.Now); inside Global.asax's Application_Start function, and Response.AddCacheItemDependency("MyCache"); inside my user control's Page_Load function.
I've then tried to invalidate it by calling another function:

    private void InvalidateCache()
    {
        HttpContext.Current.Cache.Insert("MyCache", DateTime.Now);
    }

It still didn't work.

Is there any way to invalidate UserControl's cache programmatically?

Upvotes: 1

Views: 1245

Answers (3)

VinayC
VinayC

Reputation: 49195

Use usercontrol's CachePolicy property to create a dependency on another cache key. For example, in user control code

protected void Page_Load(object sender, EventArgs e)
{
    this.CachePolicy.Dependency = new System.Web.Caching.CacheDependency(null, 
        new string[] { "KeyForThisUserControl"  });
    ...
}

And else-where to invalidate user-control's cache, use

Cache["KeyForThisUserControl"] = DateTime.Now;

where Cache refers to current web application cache.

Upvotes: 2

Edwin de Koning
Edwin de Koning

Reputation: 14387

I think the problem is that you are calling RemoveOutputCacheItem from the control itself, which would mean that the control is basically trying to remove itself from the cache...

Try calling HttpResponse.RemoveOutputCacheItem("/UserControls/SomeAction.ascx"); from another page.

Upvotes: -1

CR41G14
CR41G14

Reputation: 5594

This is possibly your problem:

Make sure you set the cache Location = "Server" otherwise it will cache on the Clients machine and then your code

HttpResponse.RemoveOutputCacheItem("/UserControls/SomeAction.ascx");

Should work?

Upvotes: 0

Related Questions