为什么在ASP.NET MVC中OutputCache是​​结果筛选器而不是操作筛选器? [英] Why is OutputCache a result filter and not an action filter in ASP.NET MVC?

查看:57
本文介绍了为什么在ASP.NET MVC中OutputCache是​​结果筛选器而不是操作筛选器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET MVC中,通常将OutputCache属性作为结果过滤器的示例. 此MSDN页面是一个地方.这样,它包装了ActionResult对象的执行.但是,该对象不是在action方法的末尾执行吗?如果它只允许在方法的末尾包装ActionResult的执行,那么我对如何使用缓存的响应以及如何阻止执行该操作本身感到困惑.我知道缓存有效,因此显然我缺少一些明显的东西.

The OutputCache attribute is commonly given as an example of a result filter in ASP.NET MVC. This MSDN page is one place. As such it wraps execution of the ActionResult object. But isn't that object executed at the end of the action method? I'm confused as to how it allows a cached response to be used and prevents the action itself from executing if it only wraps execution of the ActionResult at the end of that method. I know that caching works, so there is clearly some obvious piece that I'm missing.

推荐答案

OutputCacheAttribute继承自ActionFilterAttribute,后者又实现了IActionFilterIResultFilter.因此,OutputCacheAttribute既是动作过滤器又是结果过滤器.

The OutputCacheAttribute inherits from ActionFilterAttribute, which in turn implements IActionFilter, and IResultFilter. Thus the OutputCacheAttribute is both an action filter and a result filter.

当您考虑它时,这是很合理的.缓存背后的逻辑是这样的:

When you think about it, this makes perfect sense. The logic behind a cache goes like this:

  1. 执行时
    • 该项目在缓存中吗?
    • 如果是:从缓存返回(完成)
    • 如果否,请继续
  1. On execution
    • Is the item in the cache?
    • If Yes : return from cache (done)
    • If No, continue
  • 放入缓存
  • 返回结果

因此,第1部分是由IActionFilter的实现处理的,如果没有立即返回结果,我们将继续执行该操作,并且IResultFilter的实现将处理结果添加到缓存中以供将来调用.

So part 1 is handled by the implementation of IActionFilter, if that doesn't immediately return a result, we continue with the action and the implementation of IResultFilter handles adding that result to the cache for future calls.

由于ASP.NET是开源的,因此可以在代码中确认.在Codeplex上查看 OutputCacheAttribute.cs .

Thanks to ASP.NET being open source, this can be confirmed in code. Check out OutputCacheAttribute.cs on codeplex.

  • 第222行是在OnActionExecuting(IActionFilter的一部分)期间检查cahce的地方

  • Line 222 is where the cahce is checked during OnActionExecuting (part of IActionFilter)

第237-249行,OnActionExecuting方法设置了在OnResultExecuted(属于IResultFilter的一部分)

Line 237 - 249 the OnActionExecuting method sets up a callback that gets invoked during OnResultExecuted (part of IResultFilter)

这篇关于为什么在ASP.NET MVC中OutputCache是​​结果筛选器而不是操作筛选器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆