ASP.NET Core MVC 过滤器

参考网址:https://www.cnblogs.com/dotNETCoreSG/p/aspnetcore-4_4_3-filters.html

ASP.NET Core有五种类型的过滤器,每个过滤器类型在过滤器管道中的不同阶段执行:

  Authorization Filter:授权过滤器在过滤管道中第一个执行,通常用于验证当前请求的合法性,不合法后面的管道会直接跳过。它们只有一个Before方法,不像其它大多数过滤器支持前置阶段方法和后置阶段方法。(不要在授权过滤器中抛出异常,因为没有任何代码来处理异常)

  Resource Filter:资源过滤器是第二个运行,在Authorization Filter之后,Model Binding之前执行。在性能方面,资源过滤器在实现缓存或截断过滤器管道尤为重要。

  Action Filter:使用率最高的过滤器,在调用Action方法之前和之后执行代码。和Resource Filter类似,但Model Binding在之后执行。

  Exception Filter:用于为应用程序执行异常处理策略。

  Result Filter:当Action执行完成后,最后会执行过滤器。用于处理ActionResult结果输出策略。

过滤器运行顺序:

同步过滤器和异步过滤器:  

using FiltersSample.Helper;
using Microsoft.AspNetCore.Mvc.Filters;

namespace FiltersSample.Filters
{
    public class MyActionFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // do something before the action executes
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            // do something after the action executes
        }
    }
}

    

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;

namespace FiltersSample.Filters
{
    public class MyAsyncActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // do something before the action executes
            await next();
            // do something after the action executes
        }
    }
}

  (注意:只能实现一个类型的过滤器,要么同步过滤器,要么异步过滤器,若同时实现了两个过滤器,只有异步方法会被调用

过滤器作用域:

  过滤器具有三种不同级别的作用域。

    可以在特定的Action上使用特性Attribute的方式添加;

    可以在控制器上使用特性的方式添加,它将作用该控制器下的所有Action;

    注册一个全局过滤器,它将作用于整个MVC应用下的所有Action。

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        //options.Filters.Add(typeof(MyActionFilter)); // by type
        options.Filters.Add(new MyActionFilter()); // an instance
    });
}
//过滤器可以通过类型添加,也可以通过实例添加
//如果通过实例添加,则该实例会作用于每一次请求
//如果通过类型添加,则每一次请求都会type-actived(即每次请求都会创建该类型的实例)

 取消与短路:

  过滤器方法的上下文参数中的Result属性可以在过滤器管道的任意一点短路管道。

猜你喜欢

转载自www.cnblogs.com/az4215/p/10817703.html