如何在ASP MVC中清除指定控制器的缓存?

9

可能是重复问题:
如何以编程方式清除控制器操作方法的输出缓存

如何在指定的控制器中清除缓存?

我尝试使用几种方法:

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

没有任何效果,它不起作用。 也许有一种方法可以获取控制器缓存中的所有键,并显式地将它们移除?

我应该在哪个重写的方法中执行清除缓存操作?如何做到这一点?

有什么想法吗?

3个回答

9

你尝试过了吗?

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

}

如果这不能满足您的需求,那么可以像Mark Yu建议的那样使用自定义属性。

这在我的情况下对我起作用了...非常感谢。 - Pankaj Dubey

6

请尝试以下操作:

将以下内容添加到您的模型中:

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);
    }
}

在您具体的控制器上: 例如:
[NoCache]
[Authorize]
public ActionResult Home()
 {
     ////////...
}

source: original code


2
那个可以用,但不是立即生效的,需要等待上一个缓存过期。 - testCoder

3
试试这个:

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]);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接