如何从 api post 方法中访问 FluentValidation 错误?

How can I access FluentValidation errors from within an api post method?

Fluent Validation docs 有个例子

    public class PeopleController : Controller {
    public ActionResult Create() {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Person person) {

        if(! ModelState.IsValid) { // re-render the view when validation failed.

// 如何在此处获取验证器错误消息?

            return View("Create", person);
        }

        TempData["notice"] = "Person successfully created";
        return RedirectToAction("Index");

    }
}


public class Person {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
}

验证器设置为

public class PersonValidator : AbstractValidator<Person> {
    public PersonValidator() {
        RuleFor(x => x.Id).NotNull();
        RuleFor(x => x.Name).Length(0, 10);
        RuleFor(x => x.Email).EmailAddress();
        RuleFor(x => x.Age).InclusiveBetween(18, 60);
    }
}

假设验证失败。如何从 Create 方法中访问验证错误?

我问是因为我正在将 FluentValidation 与 API 一起使用,并且需要一种方法让 API 传达验证错误。

检查 ModelState 是否有错误(真/假)

<% YourModel.ModelState.IsValid %>

检查特定的 属性 错误

<% YourModel.ModelState["Property"].Errors %>

检查所有错误

<% YourModel.ModelState.Values.Any(x => x.Errors.Count >= 1) %>

这里有很多关于这个问题的好答案。 这是一个link to one and here is another