微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/aspnet/246233.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐