NetCore3.1 配置FluentValidation全局过滤异常
作者:互联网
一、封装全局异常过滤器实现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 { /// <summary> /// 实现异步行为验证过滤器接口 /// </summary> /// <param name="context"></param> /// <param name="next"></param> /// <returns></returns> public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (!context.ModelState.IsValid) { context.Result = new BadRequestObjectResult(context.ModelState); return; } await next(); } }
三、自定义验证器继承抽象类AbstractValidator<T>
/// <summary> /// Fluent 验证器 /// </summary> public class PostValidator:AbstractValidator<PostDto> { public PostValidator() { RuleFor(post => post.Description) .NotNull() .Length(10, 500) .WithMessage("描述信息10到500字之间"); RuleFor(post => post.Date) .NotNull() .GreaterThan(DateTime.Now); } }
四、注册验证服务
/// <summary> /// 全局注册过滤器 /// </summary> /// <param name="services"></param> /// <param name="assembyArr"></param> /// <returns></returns> public static IServiceCollection AddMvcSer(this IServiceCollection services, Assembly[] assembyArr) { services.AddMvc(options => { options.Filters.Add<ValidationFilter>(); }) .AddFluentValidation(options => { //全局注册验证器 options.RegisterValidatorsFromAssemblies(assembyArr); }); return services; }
标签:全局,FluentValidation,options,过滤,context,new,post,public,NetCore3.1 来源: https://www.cnblogs.com/ABC-wangyuhan/p/14869073.html