我有一个ASP.Net MVC5应用程序。我通过应用全局过滤器禁用了应用程序中的缓存,如下所示:
public class CachingFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache); // HTTP 1.1.
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-store, must-revalidate");
filterContext.HttpContext.Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
filterContext.HttpContext.Response.AppendHeader("Expires", "0"); // HTTP 1.0.
}
}
上面的过滤器可以很好地禁用缓存。但现在我有一个动作来填充一些统计数据作为PartialView。出于测试目的,我希望通过应用OutputCacheAttribute启用缓存20秒,如下所示:
[AcceptVerbs(HttpVerbs.Get)]
[OutputCache(Location = OutputCacheLocation.Client, Duration = 20, VaryByParam = "*")]
public PartialViewResult Statistics()
{
var stats = GetStatistics();
return PartialView("~/Views/Shared/_Statistics.cshtml", stats);
}
无论我做了什么,如果在应用程序全局中启用了CachingFilter,即使没有经过20秒的句点,也始终会调用Statistics()方法。如果我从全局禁用CachingFilter,则可以正确缓存Statistics()方法。
我认为/读取将缓存过滤器应用于操作是缓存的最终判断。如何在操作级别绕过全局缓存属性而不在全局缓存过滤器中的if子句中添加操作/控制器名称?
答案 0 :(得分:1)
您可以创建自己的属性以排除某些属性的全局过滤器,例如,创建存根属性:
public class ExcludeCacheFilterAttribute : Attribute
{
}
现在在CachingFilter
运行代码之前检查此属性:
public class CachingFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(ExcludeCacheFilterAttribute), false).Any())
{
return;
}
//Carry on with the rest of your usual caching code here
}
}