7

Possible Duplicate:
How to programmatically clear outputcache for controller action method

How to clear cache in specified controller?

I try to use several approaches:

Response.RemoveOutputCacheItem();
Response.Cache.SetExpires(DateTime.Now);

There is no any effect, it not work. :( May be exists any way to get all keys in controller cache and remove they explicitly? And in which overridden method i should perform clear cache? and how to do that?

Does any ideas?

Community
  • 1
  • 1
testCoder
  • 6,587
  • 13
  • 49
  • 72

3 Answers3

9

Have you tried

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult DontCacheMeIfYouCan()
{

}

If this doesn't do it for you then a custom attribute like Mark Yu suggests.

dove
  • 19,761
  • 14
  • 82
  • 103
6

try this:

put this on your Model:

public class NoCache : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

and on your specific controller: e.g:

[NoCache]
[Authorize]
public ActionResult Home()
 {
     ////////...
}

source: original code

Community
  • 1
  • 1
RSB
  • 239
  • 3
  • 18
2

Try this :

public void ClearApplicationCache()
{
    List<string> keys = new List<string>();

    // retrieve application Cache enumerator
    IDictionaryEnumerator enumerator = Cache.GetEnumerator(); 

    // copy all keys that currently exist in Cache
    while (enumerator.MoveNext())
    {
        keys.Add(enumerator.Key.ToString());
    }

    // delete every key from cache
    for (int i = 0; i < keys.Count; i++)
    {
        Cache.Remove(keys[i]);
    }
}
Tony
  • 13,322
  • 11
  • 66
  • 114
Chirag
  • 286
  • 2
  • 4
  • 26