Filter 筛选器之 ActionFilter-- IAsyncActionFilter 和 ActionFilterAttribute
作者:互联网
IAsyncActionFilter 使用异步actionFilter 只需要实现 他的 :OnActionExecutionAsync 方法 (注意这里的异步不是拦截异步是指的是 当前OnActionExecutionAsync方法内执行的内容是异步的)
例如:我在这里注入两个 ActionbFliter (MyActionFilter1 和 MyActionFilter2)
注意 : 多个Filter 执行是一个链路形式的
MyActionFilter1
public class MyActionFilter1 : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context,
ActionExecutionDelegate next)
{
Console.WriteLine("MyActionFilter 1:开始执行");
ActionExecutedContext r = await next(); //如果执行 下一个ActionFilter
if (r.Exception != null)
{
Console.WriteLine("MyActionFilter 1:执行失败");
}
else
{
Console.WriteLine("MyActionFilter 1:执行成功");
}
}
}
MyActionFilter2
public class MyActionFilter2 : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context,
ActionExecutionDelegate next)
{
Console.WriteLine("MyActionFilter 2:开始执行");
ActionExecutedContext r = await next();
if (r.Exception != null)
{
Console.WriteLine("MyActionFilter 2:执行失败");
}
else
{
Console.WriteLine("MyActionFilter 2:执行成功");
}
}
}
可以看到多个执行的效果
也可以使用 ActionFilterAttribute
可以看到 ActionFilterAttribute 包含了 IAsyncActionFilter 接口 和 IAsyncResultFilter 接口
例子 :
public class ActionAttribute : ActionFilterAttribute
{
private readonly ILogger<HandleActionAttribute> _logger;
public HandleActionAttribute(ILogger<ActionAttribute> logger)
{
_logger = logger;
}
// 这里需要重写父类的 virtual OnActionExecutionAsync() 方法
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
HttpRequest request = ((Microsoft.AspNetCore.Mvc.ControllerBase)context.Controller).Request;
AuthParam param = GetParameters(request);
CheckParameters(param);
//逻辑处理 省略
await base.OnActionExecutionAsync(context, next);
}
调用的时候
[TypeFilter(typeof(ActionAttribute))]
标签:ActionFilter,MyActionFilter,Console,--,OnActionExecutionAsync,next,Filter,WriteL 来源: https://www.cnblogs.com/Bo-H/p/16584380.html