标签:error var tpc ons tail ISE name detail sync
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(); } }
/// <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