2014-07-26 29 views
0


已經與這一個小時的苦苦掙扎。以下是我試圖解決:如何胸圍爲特定的控制器/動作/清晰的OutputCache在ASP.NET MVC

我有這樣的控制器/動作它採用了CacheProfile:

[DonutOutputCache(CacheProfile = "CachedAction")] 
    [ChildActionOnly] 
    public ActionResult ListOrders(string id, string selectedOrders) 
    { 
    } 

這裏是我的web.config設置:

<caching> 
    <outputCache enableOutputCache="true" /> 
    <outputCacheSettings> 
     <outputCacheProfiles> 
      <add name="CachedAction" duration="14100" varyByParam="id;selectedOrders" location="Any" /> 
     </outputCacheProfiles> 
    </outputCacheSettings> 

一切的偉大工程,使遠遠高速緩存工作如期!

問題是在我的頁面我有一個「刷新按鈕」,用戶可以點擊獲取最新的數據。爲此,我只需在用戶點擊刷新後從頁面執行$ .ajax()調用,但我調用另一個操作,因爲如果我調用原始ListOrders,我將只獲取其緩存副本。

$.ajax({ 
     url: '/controller/myajaxrefreshaorders/1?selectedOrders=xxxx', 
     type: "GET", 
     async:true, 
     cache: false, 

這是我的問題。如果你看到我只是試圖破解緩存並重定向到原始操作,應該只返回最新數據並更新緩存。但是不管我做什麼,它都不工作!

public ActionResult MyAjaxRefreshOrders(string id, string selectedOrders) 
    { 
     var Ocm = new OutputCacheManager(); 
     Ocm.RemoveItem("Controller", "ListOrders", new { id = id, selectedOrders= selectedOrders }); 
     Response.RemoveOutputCacheItem(Url.Action("ListOrders", "Controller", new { id = id, selectedOrders = selectedOrders })); 


     return RedirectToAction("ListOrders", new { id = id, selectedOrders = selectedOrders }); 
    } 

其實這是我在現實中發生的觀察:

  1. 如果我一直在重新加載頁面,緩存工作正常,它顯示的項目被檢索的最後時間的時間戳,這很棒。
  2. 如果我打的ajaxrefreshbutton,它確實去到服務器,經過我的cachebust代碼,只是返回back..i.e調用返回RedirectToAction(「ListOrders」)將不會進入該功能。
  3. 最後,看來ajaxcall會爲我創建另一個動作的緩存版本。所以,在ajax調用完成後顯示的時間戳是一個不同的時間戳,並且顯示我何時重新加載頁面的時間戳是不同的。

任何人有任何想法,我究竟做錯了什麼?我會真心感謝你的幫助,因爲這讓我瘋狂!

回答

0

回答我自己的問題。看起來這是DonutCache中的一個錯誤。這對我來說有效,就是這段代碼。 (所以基本上,我用RemoveItems而不是RemoveItem)。瘋狂!

var Ocm = new OutputCacheManager(); 
    RouteValueDictionary rv = new RouteValueDictionary(); 
    rv.Add("id", id); 
    rv.Add("selectedorders", selectedOrders); 
    Ocm.RemoveItems("controller", "listorders", rv); 

不過,由於某種原因,MVC中的RedirectToAction()將舊的緩存副本返回給客戶端。不知道是否Chrome與我或MVC搞混了。我懷疑這是Chrome與302重定向(即使我正在使用$ .ajax(cache:false))。我修復的方法是首先調用methodA(BustCache),然後調用MVC Action以獲取新鮮。數據

1
// Get the url for the action method: 
var staleItem = Url.Action("Action", "YourController", new 
{ 
    Id = model.Id, 
    area = "areaname"; 
}); 

// Remove the item from cache 
Response.RemoveOutputCacheItem(staleItem); 

此外,你需要記住的 位置= OutputCacheLocation.Server參數添加到的OutputCache 屬性,像這樣:

[OutputCache(Location=System.Web.UI.OutputCacheLocation.Server, Duration = 300, VaryByParam = "Id")] 
相關問題