2011-01-11 95 views
8

我使用的OutputCache屬性在我的MVC網站如下:旁路的OutputCache的ASP.NET MVC

[OutputCache(Duration = 5000, 
     VaryByParam = "name;region;model;id;op;content;featured;isStarred;page;size;")] 

但是有時我想完全繞過輸出緩存,並迫使從數據庫中獲取。對於我不斷將新數據加載到數據庫進行測試的測試環境,情況尤其如此。

無論如何,我可以繞過緩存在這種情況下?

感謝。

回答

2

我只需要使用緩存依賴。我需要在運行時修改這個修改,所以配置文件不是一個選項。

將以下內容添加到我想要「禁止緩存」選項的操作中。

Response.AddCacheItemDependency("Pages"); 

並創建了我可以調用以下操作來刷新緩存。

public ActionResult RefreshCache() 
    { 
     HttpContext.Cache.Insert("Pages", DateTime.Now, null, 
           DateTime.MaxValue, TimeSpan.Zero, 
           CacheItemPriority.NotRemovable, 
           null); 
     Logger.Info("Cleansed cache"); 
     return RedirectToAction("HubContent"); 
    } 
10

您可以使用OutputCache配置文件來代替在屬性中內聯指定所有輸出緩存參數。

輸出緩存配置文件允許您將所有輸出緩存設置放入web.config中,爲配置文件命名,然後從屬性中指向該配置文件。

完成設置後,您可以更改用於調試的web.config中的設置,以便緩存持續時間僅爲1秒。顯然,你會離開你的生產web.config文件的時間更長。

有關配置文件的詳細信息,請http://msdn.microsoft.com/en-us/library/hdxfb6cy.aspx

+0

您不能爲偏數執行此操作。 – 2012-12-06 14:47:02

4

如果你想將其完全關閉,你可以在你的web.config under.system.web使用

<caching> 
    <outputCache enableOutputCache="false" /> 
</caching> 

。如果你想從代碼做到這一點(使用按鈕或別的東西),你也可以這樣做:

System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/"); 
System.Web.Configuration.OutputCacheSection cacheSection = (System.Web.Configuration.OutputCacheSection)config.GetSection("system.web/caching/outputCache"); 
cacheSection.EnableOutputCache = true/false; 
config.Save(); 

這將可能只有您的開發機器上工作。大多數服務器都設置爲不允許編輯machine.config中的該部分。

+1

不會關閉它是`enableOutputCache =「false」`? – Maslow 2011-07-02 20:50:39

+0

+1 6個月後有人遇到了複製和粘貼錯誤 – 2011-07-13 14:42:18

1

這並不完全回答你的問題,但回答您的標題(這是不是「如何清除項目從緩存中 「): 你可以添加一個」 VaryByParam「:

[OutputCache(Duration=5000,VaryByParam="YourExistingParams;CacheBypass")] 

那麼y時ou想要繞過緩存,只需傳遞CacheBypass參數DateTime.UtcNow.Ticks(或任何隨機事物)的值=>例如:http://localhost/?CacheBypass=1234567890