如何在ASP.NET MVC中为特定的Controller / Action声明/清除OutputCache

时间:2014-07-26 17:19:56

标签: asp.net-mvc asp.net-mvc-4 caching output-caching


几个小时以来一直在努力奋斗这个。这是我想要解决的问题:

我有这个控制器/动作使用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代码并简单地返回..即返回RedirectToAction(“ListOrders”)的调用永远不会进入该函数。
  3. 最后,似乎ajaxcall为我创建了另一个缓存版本的操作。因此,在ajax调用完成后显示的时间戳是一个不同的时间戳,并且显示我重新加载页面时的时间戳是不同的。
  4. 任何人都有任何想法我做错了什么?我将非常感谢你的帮助,因为这让我疯了!

2 个答案:

答案 0 :(得分: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);
  

此外,您需要记住添加   Location = OutputCacheLocation.Server参数到OutputCache   属性,像这样:

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

答案 1 :(得分: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以获得新的数据