过滤器的作用是在 Action 方法执行前或执行后做一些加工处理。使用过滤器可以避免Action方法的重复代码,例如,您可以使用异常过滤器合并异常处理的代码。
过滤器如何工作?
过滤器在 MVC Action 调用管道中运行,有时称为过滤器管道。MVC选择要执行的Action方法后,才会执行过滤器管道:

实现
过滤器同时支持同步和异步两种不同的接口定义。您可以根据执行的任务类型,选择同步或异步实现。
同步过滤器定义OnStageExecuting和OnStageExecuted方法,会在管道特定阶段之前和之后运行代码的。例如IActionFilter过滤器,在调用Action方法之前调用OnActionExecuting,在Action方法之回之后调用OnActionExecuted:
public class SampleActionFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { // do something before the action executes } public void OnActionExecuted(ActionExecutedContext context) { // do something after the action executes } }异步过滤器定义了一个OnStageExecutionAsync方法。该方法提供了FilterTypeExecutionDelegate的委托,当调用该委托时会执行具体管道阶段的工作。例如,ActionExecutionDelegate用于调用Action方法,您可以在调用它之前和之后执行代码。
public class SampleAsyncActionFilter : IAsyncActionFilter { public async Task OnActionExecutionAsync( ActionExecutingContext context, ActionExecutionDelegate next) { // do something before the action executes await next(); // do something after the action executes } }您可以在单个类中实现多个过滤器接口。例如,ActionFilterAttribute抽象类实现了IActionFilter和IResultFilter,以及与它们对应的异步接口。
滤器之前执行前置方法;具有较低
Order值的过滤器将在具有较高Order值的过滤器之后执行后置方法。
您可以使用构造函数参数设置Order属性:[MyFilter(Name = "Controller Level Attribute", Order=1)]如果您将上述示例中 Action 过滤器的
Order设置为1,将控制器和全局过滤器的Order属性分别设置为2和3,则执行顺序将与默认相反。
序号 过滤器作用域 Order属性过滤器方法 1 Method 1 OnActionExecuting2 Controller 2 OnActionExecuting3 Global 3 OnActionExecuting4 Global 3 OnActionExecuted5 Controller 2 OnActionExecuted6 Method 1 OnActionExecuted过滤器执行时,
Order属性的优先级高于作用域。过滤器首先按Order属性排序,然后再按作用域排序。所有内置过滤器实现IOrderedFilter接口并将Order值默认设置为0;因此,除非设置Order属性为非零值,否则按作用域的优先级执行。到此这篇关于ASP.NET Core MVC中过滤器工作原理的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。








