程序猿改变世界
首先需要定义一个Action过滤器类,如命名为:MyActionFilter,继承IActionFilter(同步)或IAsyncActionFilter(异步)接口,这里以IAsyncActionFilter为例,如图:
然后在Program.cs中注册自定义的Action过滤器:
builder.Services.Configure<MvcOptions>(options => { //注册自定义的Actioin过滤器 options.Filters.Add<MyActionFilter>(); });
控制台输出如下:
如果添加多个Action过滤器呢? 效果是什么样的?这里添加了三个Action过滤器
builder.Services.Configure<MvcOptions>(options => { //注册自定义的Actioin过滤器 options.Filters.Add<MyActionFilter>(); options.Filters.Add<MyActionFilter2>(); options.Filters.Add<MyActionFilter3>(); });
MyActionFilter2:
public class MyActionFilter2 : IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { Console.WriteLine("MyActionFilter2 Begin"); //执行真正要执行的Action ActionExecutedContext nextContext = await next(); //通过Exception判断Action是否执行成功 if (nextContext.Exception != null) Console.WriteLine("Action执行异常!"); else Console.WriteLine("Action执行成功!"); Console.WriteLine("MyActionFilter2 End"); } }
MyActionFilter3:
public class MyActionFilter3 : IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { Console.WriteLine("MyActionFilter3 Begin"); //执行真正要执行的Action ActionExecutedContext nextContext = await next(); //通过Exception判断Action是否执行成功 if (nextContext.Exception != null) Console.WriteLine("Action执行异常!!"); else Console.WriteLine("Action执行成功!!"); Console.WriteLine("MyActionFilter3 End"); } }
执行效果如下:
有点像俄罗斯套娃
来源:时间去哪儿了博客(微信/QQ号:903918446),转载请保留出处和链接!
本文链接:http://timegowhere.com/post/netcore-action-filter.html
【个人微信】
【时间去哪儿了】
教育类博客,关注知识的分享与交流。
欢迎关注公众号!
加我微信
Copyright © 2014-2022 timegowhere.com. All rights reserved. 粤ICP备15081222号