.Net Core AOP之IResultFilter
一、简介
在.net core 中Filter分为以下六大类:
1、AuthorizeAttribute(权限验证)
2、IResourceFilter(资源缓存)
3、IActionFilter(执行方法前后的记录)
4、IResultFilter(结果生成前后扩展)
5、IAlwaysRun(响应结果的补充)
6、IExceptionFilter(异常处理)
二、IResultFilter(同步)
1、定义Filter
public class CustomerResultFilterAttribute : Attribute, IResultFilter { /// <summary> /// 在xx结果之前 /// </summary> /// <param name="context"></param> /// <exception cref="NotImplementedException"></exception> public void OnResultExecuting(ResultExecutingContext context) { Console.WriteLine("CustomerResultFilterAttribute.OnResultExecuting"); if(context.Result is JsonResult) { JsonResult result= (JsonResult)context.Result; context.Result = new JsonResult(new { Data= result.Value, Success=true }); } } /// <summary> /// 在xx结果之后 /// </summary> /// <param name="context"></param> /// <exception cref="NotImplementedException"></exception> public void OnResultExecuted(ResultExecutedContext context) { Console.WriteLine("CustomerResultFilterAttribute.OnResultExecuted"); } }
2、使用Filter
public class Home2Controller : Controller { private readonly ILogger<Home2Controller> _logger; public Home2Controller(ILogger<Home2Controller> logger) { _logger = logger; Console.WriteLine($"执行 {this.GetType().Name} 构造函数"); } [CustomerResultFilter] // 当Filter中有构造函数时,需这样调用:[TypeFilter(typeof(CustomerResultFilterAttribute))] public IActionResult Index() { Console.WriteLine($"执行 Index 方法"); return Json(new { id="11",name="heheh"}); } }
三、IAsyncResultFilter(异步)
public class CustomerAsyncResultFilterAttribute : Attribute, IAsyncResultFilter { public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { if (context.Result is JsonResult) { JsonResult result = (JsonResult)context.Result; context.Result = new JsonResult(new { Data = result.Value, Success = true }); } await next.Invoke(); // 这里及时去渲染结果去了 } }
四、总结
作用:适用于统一返回Action的结果格式,JSON格式的统一处理
执行顺序 1、先执行Action 方法结束
2、CustomerResultFilterAttribute.OnResultExecuting 3、渲染试图或返回Action结果 4、CustomerResultFilterAttribute.OnResultExecuted