gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:43:09 25 4
gpt4 key购买 nike

我已将输出缓存添加到我的应用程序中的几个操作中,以实现一些简单的性能提升。但是,这些操作还需要在每个请求(它是一个 View 计数器)之后通过命中 Redis 数据库来增加一个计数器。

起初,我想我可以调整操作过滤器执行的顺序以确保计算 View :

public class CountersAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
//increment my counter all clever like
base.OnResultExecuted(filterContext);
}
}

但这没有用;显然 OutputCacheAttribute 的行为不像正常的 Action 过滤器。然后我尝试实现自定义输出缓存:
public class OutputCacheWithCountersAttribute : OutputCacheAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
//straight to the source to get my headcount!
base.OnResultExecuted(filterContext);
}
}

不,也没有用;一旦操作被缓存,操作过滤器似乎被完全忽略。无赖。

那么,呃,有没有什么办法(不实现自定义输出缓存提供程序)让我确保我的 View 被正确计算,干净而合理?

最佳答案

OutputCacheAttribute顺便说一下,有一个名为 DonutOutputCache 的自定义属性。由 Paul Hiles 开发有助于克服这些限制。

它支持的重要功能之一是您可以拥有一个可以一直调用的 Action 过滤器,即使该 Action 是否标记有缓存属性。

例如。你想要缓存一个 Action 5 秒,同时你想要在每次 Action 接收到使用 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.

关于asp.net-mvc - 使用输出缓存和其他操作过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10990337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com