#region 添加全局异常过滤器和参数校验过滤器 services.AddControllers(options => { options.Filters.
Add<ValidFilterAttribute>(); options.Filters.Add<GlobalExceptionFilter>(); }); #
endregion
ValidFilterAttribute
//参数校验 public class ValidFilterAttribute : BaseActionFilterAsync { public
override async Task OnActionExecuting(ActionExecutingContext context) { if (!
context.ModelState.IsValid) { var msgList = context.ModelState.Values.SelectMany
(x => x.Errors).Select(x => x.ErrorMessage); context.Result = Error(string.Join(
",", msgList)); } await Task.CompletedTask; } }
GlobalExceptionFilter
//全局错误异常校验 public class GlobalExceptionFilter : BaseActionFilterAsync,
IAsyncExceptionFilter{ readonly ILogger _logger; public GlobalExceptionFilter(
ILogger<GlobalExceptionFilter> logger) { _logger = logger; } public async Task
OnExceptionAsync(ExceptionContext context) { Exception ex = context.Exception;
if (ex is BusException busEx) { _logger.LogInformation(busEx.Message); context.
Result= Error(busEx.Message, busEx.ErrorCode); } else { _logger.LogError(ex, "")
; context.Result = Error(ex.Message); } await Task.CompletedTask; } }
BaseActionFilterAsync
public abstract class BaseActionFilterAsync : Attribute, IAsyncActionFilter {
public async virtual Task OnActionExecuting(ActionExecutingContext context) {
await Task.CompletedTask; } public async virtual Task OnActionExecuted(
ActionExecutedContext context) { await Task.CompletedTask; } public async Task
OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate
next) { await OnActionExecuting(context); if (context.Result == null) { var
nextContext= await next(); await OnActionExecuted(nextContext); } } }

技术
©2019-2020 Toolsou All rights reserved,
MySQL触发器【linux】shell:简单的shell脚本练习java连接数据库实现基本的增删改查Windows网络服务渗透测试实战-跨网段攻击JavaScript百炼成仙 1.15 天秀idea运行Mybatis项目出现的常见错误(编码错误等)Java实现自动猜数(猜数游戏进阶版)VHDL——4位移位寄存器【微信小程序学习】网易云音乐歌曲详情页代码实现一份笔记让你从 15K 涨薪并跳槽到32K+16