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.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....