有没有一种程序化的方式可以使ASP.NET MVC输出缓存的部分失效? 我希望能够做到的是,如果用户发布了更改缓存动作返回结果的数据,则能够使该缓存数据失效。
这是否有可能?
这是否有可能?
一种方法是使用以下方法:
HttpResponse.RemoveOutputCacheItem("/Home/About");
这里还有另一种方法:http://aspalliance.com/668
我认为你可以通过为每个要添加的操作使用方法级别的属性,并将表示键的字符串添加到其中,来实现第二种方法。前提是我理解了你的问题。
编辑:是的,asp.net mvc的OutputCache只是一个包装器。
如果你正在使用varyByParam="none"
,那么你只需使"/Statistics"
失效 - 如果<id1>/<id2>
是查询字符串值的话。这将使所有版本的页面都失效。
我进行了快速测试,如果你添加了varyByParam="id1"
,然后创建了多个页面版本 - 如果你说使"/Statistics/id1"
失效,则仅使该版本失效。但你应该做进一步的测试。
我对缓存做了一些测试,以下是我的结论:
必须为到达您的操作的每个路由清除缓存。如果您有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
:
如果我的操作如下
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));
}