/// <summary> /// 统一模型验证 /// <para>控制器必须添加 [ApiController] 才能被此过滤器拦截</para> /// </summary> /// <param name="services"></param> public static void GlabalInvalidModelStateFilter(this IServiceCollection services) { services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { if (actionContext.ModelState.IsValid) { return(new BadRequestObjectResult(actionContext.ModelState)); } int count = actionContext.ModelState.Count; ValidationErrors[] errors = new ValidationErrors[count]; int i = 0; foreach (var item in actionContext.ModelState) { errors[i] = new ValidationErrors { Member = item.Key, Messages = item.Value.Errors?.Select(x => x.ErrorMessage).ToArray() }; i++; } // 响应消息 var result = ApiResponseModel.Create(HttpStateCode.Status400BadRequest, CommonResponseType.BadRequest, errors); var objectResult = new BadRequestObjectResult(result); objectResult.StatusCode = StatusCodes.Status400BadRequest; return(objectResult); }; }); }
public async Task OnExceptionAsync(ExceptionContext context) { if (!context.ExceptionHandled) { ApiResponseModel model = ApiResponseModel.Create( HttpStateCode.Status500InternalServerError, CommonResponseType.Status500InternalServerError); context.Result = new ContentResult { Content = JsonConvert.SerializeObject(model), StatusCode = StatusCodes.Status200OK, ContentType = "application/json; charset=utf-8" }; } context.ExceptionHandled = true; await Task.CompletedTask; }
public async Task OnExceptionAsync(ExceptionContext context) { if (!context.ExceptionHandled) { await _localEventBus.PublishAsync(new CustomerExceptionEvent(context.Exception, context.ActionDescriptor?.DisplayName)); ApiResponseModel model = ApiResponseModel.Create( HttpStateCode.Status500InternalServerError, CommonResponseType.Status500InternalServerError); context.Result = new ContentResult { Content = JsonConvert.SerializeObject(model), StatusCode = StatusCodes.Status200OK, ContentType = "application/json; charset=utf-8" }; } context.ExceptionHandled = true; await Task.CompletedTask; }