2009-08-17 82 views
46

有没有办法编程无效ASP.NET MVC输出缓存的部分?我希望能够做的是,如果用户发布更改缓存操作返回内容的数据,则可以使缓存的数据无效。如何“无效”ASP.NET MVC输出缓存的部分?

这甚至可能吗?

+2

你找到一个解决? – Stefanvds 2011-02-06 10:00:41

+0

重复:http://stackoverflow.com/questions/1200616/abort-outputcache-duration-programatically-in-asp-net-mvc和http://stackoverflow.com/questions/1167890/how-to-programmatically- clear-outputcache-for-controller-action-method – 2011-03-15 20:07:03

回答

39

的方法之一是使用方法:

HttpResponse.RemoveOutputCacheItem("/Home/About"); 

这里描述的另一种方法:http://aspalliance.com/668

我想你可以通过使用你想要的每一个动作的方法级别属性实现第二个方法只需添加表示键的字符串即可。那就是如果我理解你的问题。

编辑:是的,asp.net mvc OutputCache只是一个包装。

如果您使用varyByParam="none"那么您只需使"/Statistics"无效 - 即如果<id1>/<id2>是查询字符串值。这将使所有版本的页面无效。

我做了一个快速测试,如果您添加varyByParam="id1",然后创建多个版本的页面 - 如果您认为无效"/Statistics/id1"它将使该版本无效。但你应该做进一步的测试。

+1

是MVC OutputCache属性,仅仅是一般的ASP.NET输出缓存的包装?因此,假设我想要使称为“/ Statistics//”的操作的结果无效,我只需调用HttpResponse.RemoveOutputCacheItem(“/ Statistics//”)? FWIW,属性的“VaryByParams”属性为“无”。我是否正确使用该属性? – 2009-08-17 21:19:13

+0

@Matthew Belk:你最终使用了这种技术吗?按照预期,缓存项的无效化是否按预期工作?谢谢。 – UpTheCreek 2011-01-22 10:20:26

+0

我会推荐使用MvcDonutCaching,更多信息可在这里http://www.devtrends.co.uk/blog/donut-output-caching-in-asp.net-mvc-3 – 2012-08-02 19:09:42

1

我做了一些缓存测试。这是我发现的:

您必须清除导致您的操作的每条路径的缓存。 如果您有3条路径导致控制器中的动作完全相同,则每条路由都有一个缓存。

比方说,我有这样的路线配置:

routes.MapRoute(
       name: "config1", 
       url: "c/{id}", 
       defaults: new { controller = "myController", action = "myAction", id = UrlParameter.Optional } 
       ); 

      routes.MapRoute(
       name: "Defaultuser", 
       url: "u/{user}/{controller}/{action}/{id}", 
       defaults: new { controller = "Accueil", action = "Index", user = 0, id = UrlParameter.Optional } 
      ); 

      routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Accueil", action = "Index", id = UrlParameter.Optional } 
      ); 

随后,这3种途径导致myActionmyController与帕拉姆myParam

  1. http://example.com/c/myParam
  2. http://example.com/myController/myAction/myParam
  3. http://example.com/u/0/myController/myAction/myParam

如果我的行为是遵循

public class SiteController : ControllerCommon 
    { 

     [OutputCache(Duration = 86400, VaryByParam = "id")] 
     public ActionResult Cabinet(string id) 
     { 
      return View(); 
} 
} 

我会为每个路由(在这种情况下,3)一个高速缓存。因此,我必须使每条路线无效。

像这样

private void InvalidateCache(string id) 
     { 
      var urlToRemove = Url.Action("myAction", "myController", new { id}); 
      //this will always clear the cache as the route config will create the path 
      Response.RemoveOutputCacheItem(urlToRemove); 
      Response.RemoveOutputCacheItem(string.Format("/myController/myAction/{0}", id)); 
      Response.RemoveOutputCacheItem(string.Format("/u/0/myController/myAction/{0}", id)); 
     }