asp.net-mvc – 使用输出缓存和其他动作过滤器

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 使用输出缓存和其他动作过滤器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经在我的应用程序中添加了“输出缓存”,以实现一些简单的性能提升.但是,这些操作还需要在每个请求之后增加一个计数器(它是一个视图计数器),方法是点击一个Redis db.

起初,我想我可以调整操作过滤器执行的顺序,以确保视图被计数:

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

不,也不行一旦缓存了一个动作,操作过滤器就会被完全忽略.游民.

那么,呃,有没有办法(没有实现一个自定义输出缓存提供程序),以确保我的意见被正确地计数是干净和明智的?

解决方法

OutputCacheAttribute有一些限制,并且有一个由Paul Hiles开发的名为 DonutOutputCache自定义属性帮助克服了这些限制.

支持的一个重要功能就是可以使用一个动作过滤器,即使动作标记有缓存属性也可以一直调用.

例如您希望缓存一段时间为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.

原文链接:https://www.f2er.com/aspnet/246233.html

猜你在找的asp.Net相关文章