我正在使用 FluentValidation 库来自动验证运行良好的模型 - 但是 - 需要使用WithErrorCode()验证器 ( AbstractValidator<T>) 中的方法设置错误代码。这也可以正常工作,然后问题是从定义如下的 ASP.NET MVC Core Action Filter 检索该代码:
public class ActionModelValidationAttribute : ActionFilterAttribute
{
readonly ILogger<ActionModelValidationAttribute> log;
public ActionModelValidationAttribute (ILogger<ActionModelValidationAttribute> log) => this.log = log;
public override void OnActionExecuting (ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var routeName = context.RouteData.Values["action"] ?? "unknown";
log.LogDebug($"model validation failed for {routeName}");
var errors = context.ModelState.Values.Where(state => state.Errors.Count > 0)
.SelectMany(errs => errs.Errors)
.Select(e => new BaseErrorResponse(){
Code = 404, // <<-- this is where I would like the code from WithErrorCode()
Details = e.Exception?.Message ?? "",
Message = e.ErrorMessage,
Field = "field"
}).ToList();
var response = new ValidationErrorResponseModel()
{
Message = "Bad Request",
Errors = errors
};
context.Result = new JsonResult(response)
{
StatusCode = (int)HttpStatusCode.BadRequest
};
}
}
}
错误的类型是 Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateEntry
e 的类型是 Microsoft.AspNetCore.Mvc.ModelBinding.ModelError
这是我的验证器:
public class ViewModelValidator : AbstractValidator<ViewModel>
{
public ViewModelValidator() {
RuleFor(m => m.DistributorId)
.NotNull().WithErrorCode("910000")
.NotEmpty().WithErrorCode("910001");
}
}