NetCore3.1 配置FluentValidation全局过滤异常

2021-08-12 00:57

阅读:555

标签:error   var   tpc   ons   tail   ISE   name   detail   sync   一、封装全局异常过滤器实现IExceptionFilter接口 public class GlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { if (context.Exception.GetType() == typeof(BusinessException)) { var exception = (BusinessException)context.Exception; var validation = new { Status = 400, Title = "BadRequest", Detail = exception.Message }; var json = new { errors = new[] { validation } }; context.Result = new BadRequestObjectResult(json); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.ExceptionHandled = true; } } } 二、全局处理模型绑定 public class ValidationFilter : IAsyncActionFilter { /// /// 实现异步行为验证过滤器接口 /// /// /// /// public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (!context.ModelState.IsValid) { context.Result = new BadRequestObjectResult(context.ModelState); return; } await next(); } } 三、自定义验证器继承抽象类AbstractValidator /// /// Fluent 验证器 /// public class PostValidator:AbstractValidator { public PostValidator() { RuleFor(post => post.Description) .NotNull() .Length(10, 500) .WithMessage("描述信息10到500字之间"); RuleFor(post => post.Date) .NotNull() .GreaterThan(DateTime.Now); } } 四、注册验证服务 /// /// 全局注册过滤器 /// /// /// /// public static IServiceCollection AddMvcSer(this IServiceCollection services, Assembly[] assembyArr) { services.AddMvc(options => { options.Filters.Add(); }) .AddFluentValidation(options => { //全局注册验证器 options.RegisterValidatorsFromAssemblies(assembyArr); }); return services; }  NetCore3.1 配置FluentValidation全局过滤异常标签:error   var   tpc   ons   tail   ISE   name   detail   sync   原文地址:https://www.cnblogs.com/ABC-wangyuhan/p/14869073.html


评论


亲,登录后才可以留言!