如何“使无效”ASP.NET MVC输出缓存的部分?

47
有没有一种程序化的方式可以使ASP.NET MVC输出缓存的部分失效? 我希望能够做到的是,如果用户发布了更改缓存动作返回结果的数据,则能够使该缓存数据失效。
这是否有可能?

重复的问题:https://dev59.com/R0jSa4cB1Zd3GeqPHKd5和https://dev59.com/_nM_5IYBdhLWcg3w6X1e - Drew Noakes
2个回答

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/<id1>/<id2>"操作的结果无效,我只需调用HttpResponse.RemoveOutputCacheItem("/Statistics/<id1>/<id2>")即可吗?顺便说一下,该属性的“VaryByParams”属性为“None”。我是否正确使用了该属性? - Matthew Belk
@Matthew Belk:最终你使用了这种技术吗?按参数使缓存项失效是否如预期一样工作?谢谢。 - UpTheCreek
我建议使用MvcDonutCaching,更多信息请参见http://www.devtrends.co.uk/blog/donut-output-caching-in-asp.net-mvc-3。 - Pierluc SS
ASP Alliance的链接已经失效。 - cbp

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 }
            );

然后,这三个路由都会导向myController中的myAction,参数为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));
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接