(精华)2020年7月21日 ASP.NET Core 全局过滤器的使用

#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);
         }
     }
}

你可能感兴趣的:(#,ASP.NET,Core,c#,asp.net,后端)