起初,我想我可以调整操作过滤器执行的顺序,以确保视图被计数:
public class CountersAttribute : ActionFilterAttribute { public override void OnResultExecuted(ResultExecutedContext filterContext) { //increment my counter all clever like base.OnResultExecuted(filterContext); } }
但那没有办法显然OutputCacheAttribute的行为不像正常的动作过滤器.然后我尝试实现自定义输出缓存:
public class OutputCacheWithCountersAttribute : OutputCacheAttribute { public override void OnResultExecuted(ResultExecutedContext filterContext) { //straight to the source to get my headcount! base.OnResultExecuted(filterContext); } }
不,也不行一旦缓存了一个动作,操作过滤器就会被完全忽略.游民.
解决方法
它支持的一个重要功能就是可以使用一个动作过滤器,即使动作标记有缓存属性也可以一直调用.
例如您希望缓存一段时间为5秒的动作,同时您希望在每次使用LogThis过滤器接收到请求时记录,您可以通过以下方式实现该操作,
[LogThis] [DonutOutputCache(Duration=5,Order=100)] public ActionResult Index()
从Paul,
Yes,unlike the built-in OutputCacheAttribute,the action filters will
execute even when a page is retrieved from the cache. The only caveat
to add is that you do need to be careful about the filter order. If
your action filter implements OnResultExecuting or OnResultExecuted
then these methods will be executed in all cases,but for
OnActionExecuting and OnActionExecuted,they will only be executed if
the filter runs before the DonutOutputCacheAttribute. This is due to
the way that MVC prevents subsequent filters from executing when you
set the filterContext.Result property which is what we need to do for
output caching.I do not think that you can rely on the order in which action filters
are defined on an action or controller. To ensure that one filter runs
before another,you can make use of the Order property that is present
on all ActionFilterAttribute implementations. Any actions without the
order property set,default to an value of -1,meaning that they will
execute before filters which have an explicit Order value.Therefore,in your case,you can just add Order=100 to the DonutOutputCache attribute and all other filters will execute before the caching filter.