【问题标题】:How to clear cache in specified controller in asp mvc? [duplicate]如何在asp mvc中清除指定控制器中的缓存? [复制]
【发布时间】:2012-09-28 09:26:24
【问题描述】:

可能重复:
How to programmatically clear outputcache for controller action method

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

我尝试使用几种方法:

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

没有任何效果,它不起作用。 :( 可能存在任何方式来获取控制器缓存中的所有键并明确删除它们? 我应该在哪种覆盖方法中执行清除缓存?以及如何做到这一点?

有什么想法吗?

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc caching


    【解决方案1】:

    你试过了吗

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

    如果这不适合你,那么像 Mark Yu 这样的自定义属性建议。

    【讨论】:

    • 这在我的场景中对我有用......非常感谢......
    【解决方案2】:

    试试这个:

    把它放在你的模型上:

    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()
     {
         ////////...
    }
    

    来源:original code

    【讨论】:

    • 有效但不是立即生效,需要等待最后一个缓存过期。
    【解决方案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]);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2020-08-11
      • 2018-02-16
      • 2021-02-05
      • 2018-05-01
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多