asp.net-mvc 过滤器在 asp.net mvc 中执行的顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6561883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In what order are filters executed in asp.net mvc
提问by Muhammad Adeel Zahid
In MVC we can decorate action methods with different filters like
在 MVC 中,我们可以使用不同的过滤器来装饰操作方法,例如
[HttpPost]
[Authorize]
public ActionResult mymethod(){}
HttpPost
derives from MethodSelectorAttribute
(probably indirectly) and the Authorize
attribute inherits from ActionFilterAttribute
.
HttpPost
派生自MethodSelectorAttribute
(可能是间接的)并且Authorize
属性继承自ActionFilterAttribute
。
My question is: in which order are they executed in the MVC request pipeline? I tried to go search in MVC source code but failed to find the relevant code bits.
我的问题是:它们在 MVC 请求管道中以什么顺序执行?我试图在 MVC 源代码中搜索,但未能找到相关的代码位。
回答by Eranga
Filters run in the following order:
过滤器按以下顺序运行:
- Authorization filters
- Action filters
- Response filters
- Exception filters
- 授权过滤器
- 动作过滤器
- 响应过滤器
- 异常过滤器
For example, authorization filters run first and exception filters run last. Within each filter type, the Order value specifies the run order. Within each filter type and order, the Scope enumeration value specifies the order for filters. This enumeration defines the following filter scope values (in the order in which they run):
例如,授权过滤器首先运行,异常过滤器最后运行。在每个过滤器类型中,Order 值指定运行顺序。在每个过滤器类型和顺序中,Scope 枚举值指定过滤器的顺序。此枚举定义了以下过滤器范围值(按它们运行的顺序):
- First
- Global
- Controller
- Action
- Last
- 第一的
- 全球的
- 控制器
- 行动
- 最后的
Extracted from MSDN
摘自MSDN
回答by ProVega
To save you some time, this is how you set the order:
为了节省您的时间,您可以通过以下方式设置订单:
[MyCustomContextFilter(Order=1)]
The index is 0 based, so you can do 0, 1, 2, etc...
索引是基于 0 的,因此您可以执行 0、1、2 等...
It should be noted that just because a filter is on the base class doesn't tell MVC to apply it first :(.
应该注意的是,仅仅因为过滤器在基类上并不会告诉 MVC 首先应用它:(。