2014-07-26 76 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")] 
相关问题