2009-08-17 80 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)); 
     }