码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2021-06-10 18:02:47      阅读:0      评论:0      收藏:0      [点我收藏+]

标签: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
    {
        /// <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;
        }

 

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

标签:error   var   tpc   ons   tail   ISE   name   detail   sync   

原文地址:https://www.cnblogs.com/ABC-wangyuhan/p/14869073.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!