/// <summary> /// 设置验证失败结果 /// </summary> /// <param name="context">动作方法执行上下文</param> /// <param name="modelState">模型验证状态</param> /// <param name="actionDescriptor"></param> /// <param name="isMvcController"></param> private static void SetValidateFailedResult(ActionExecutingContext context, ModelStateDictionary modelState, ControllerActionDescriptor actionDescriptor, bool isMvcController) { // 解析验证消息 var(validationResults, validateFaildMessage, _) = ValidatorContext.OutputValidationInfo(modelState); // 判断是否跳过规范化结果 if (isMvcController || UnifyContext.IsSkipUnifyHandler(actionDescriptor.MethodInfo, out var unifyResult)) { // 返回 400 错误 var result = new BadRequestObjectResult(modelState); // 设置返回的响应类型 result.ContentTypes.Add(MediaTypeNames.Application.Json); result.ContentTypes.Add(MediaTypeNames.Application.Xml); context.Result = result; } else { context.Result = unifyResult.OnValidateFailed(context, modelState, validationResults, validateFaildMessage); } // 打印验证失败信息 if (!isMvcController) { App.PrintToMiniProfiler(MiniProfilerCategory, "Failed", $"Validation Failed:\r\n{validateFaildMessage}", true); } }
/// <summary> /// 动作方法执行之前操作 /// </summary> /// <param name="context"></param> public void OnActionExecuting(ActionExecutingContext context) { // 获取控制器/方法信息 var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; // 跳过验证类型 var nonValidationAttributeType = typeof(NonValidationAttribute); var method = actionDescriptor.MethodInfo; // 如果参数为 0或贴了 [NonValidation] 特性 或所在类型贴了 [NonValidation] 特性,则跳过验证 if (actionDescriptor.Parameters.Count == 0 || method.IsDefined(nonValidationAttributeType, true) || method.DeclaringType.IsDefined(nonValidationAttributeType, true)) { return; } // 获取验证状态 var modelState = context.ModelState; // 判断是否验证成功 if (modelState.IsValid) { return; } // 如果其他过滤器已经设置了结果,那么跳过 if (context.Result != null) { return; } // 解析验证消息 var validationMetadata = ValidatorContext.GetValidationMetadata(modelState); // 判断是否跳过规范化结果,如果跳过,返回 400 BadRequestResult if (UnifyContext.CheckFailedNonUnify(actionDescriptor.MethodInfo, out var unifyResult)) { context.Result = new BadRequestResult(); } else { // 判断是否支持 MVC 规范化处理 if (!UnifyContext.CheckSupportMvcController(context.HttpContext, actionDescriptor, out _)) { return; } context.Result = unifyResult.OnValidateFailed(context, validationMetadata); } // 打印验证失败信息 App.PrintToMiniProfiler("validation", "Failed", $"Validation Failed:\r\n{validationMetadata.Message}", true); }