FluentValidation 在错误的时间进行验证

FluentValidation doing validation at the wrong time

我在我的 MVC 网站上设置了 FluentValidation。我的一个对象具有使用 Must 命令调用函数的验证检查:

RuleFor(m => m).Must(m => reimbursementMonthsRequired(m)).WithMessage("Wrong!").WithName("ReimbursementStartMonth");

remairmentMonthsRequired 函数检查对象上的值和对象下的集合以确定有效性。

我有一个 Post 方法接受用于更新该集合的值列表:

[HttpPost]
public ActionResult AddGrant(Grant item, List<byte> reimbursementMonths)
{
  item.UpdateReimbusementMonths(Database, reimbursementMonths);
  if (ModelState.IsValid)
  {     
    Database.Grants.Add(item);
    Database.SaveChanges();
    ...

我遇到的问题是,在此函数中,在调用 UpdateReimbusementMonths 之前调用了验证检查。因此,我需要用于验证检查正常工作的数据还不存在。奇怪的是,在我的编辑函数中,验证发生在我调用 UpdateReimbursementMonths 之后,因此它可以正常工作。这就是它正在做的事情:

[HttpPost]
public ActionResult EditGrant(int id, List<byte> reimbursementMonths)
{
  var item = Database.Grants.Find(id);
  item.UpdateReimbusementMonths(Database, reimbursementMonths);
  TryUpdateModel(item);
  if (ModelState.IsValid)
  ... 

那么如何让我的 Add 函数在适当的时间进行验证 - 在函数调用更新集合之后?看来,如果我可以在该函数调用后重新运行 验证检查,那就行得通了。

根据documentation

工作

在 AddGrant 方法中,您将发布 Grant 对象,因此它会在自动绑定后执行验证,然后再执行您的操作方法中的任何代码。

-> 您要么必须在发布之前用报销更新 Grant,要么删除流畅的验证并在操作方法中手动执行此验证。

-> 另一种选择是编写自定义 Validator Interceptors 并在 BeforeMvcValidation 方法中使用 Reimbursements 更新 Grant 项目。 (这可能是一种 hack,并不理想)

我发现让 AddGrant 方法执行类似于 EditGrant 的操作是有效的。我没有将 Grant 对象作为方法参数,而是这样做的:

public ActionResult AddGrant(List<byte> reimbursementMonths)
{      
  var item = new Grant();
  item.UpdateReimbusementMonths(Database, reimbursementMonths);
  TryUpdateModel(item);

  if (ModelState.IsValid)
  {     
    ...

幸运的是,我没有在 UpdateReimbusementMonths 方法中使用 Grant 对象的任何值。如果我这样做了,我就必须想出别的办法,因为显然 TryUpdateModel 会触发验证过程。