手动 FluentValidation 无需验证两次

问题描述 投票:0回答:1

FluentValidation 的建议是使用手动验证:

https://docs.fluidation.net/en/latest/aspnet.html 上,您可以看到自动方法已被弃用:

我们不再建议在新项目中使用此方法,但它仍然可用于旧实现。

并且推荐手动方法:

通过手动验证,您可以将验证器注入控制器中 (或 api 端点),调用验证器并根据结果采取行动。这 是最直接的方法,也是最容易看到的方法 发生了什么事。

我完全同意这种方式更干净、更容易理解。

但是在使用 FluentValidation 进行手动验证之前发生的内置模型验证又如何呢?如果我使用 FluentValidation 实现一个非常复杂的验证器,则可能会发生内置验证器已经向模型状态添加验证错误并且自定义验证器不会被触发的情况。结果是模型的验证不完整。但我更喜欢完全验证模型,并防止每次返回一组不同的消息。

如何防止这样的双重验证?是否应该停用内置验证器,或者除了自动方法之外是否有其他方法仅使用 FluentValidation 验证器?

c# asp.net-core validation fluentvalidation modelstate
1个回答
0
投票

FluentValidation 具有内置扩展

.AddToModelState()
,因此可以将 Fluent 验证器的验证错误添加到 ASP.NET Core 验证的错误中。他们文档中的示例:

[HttpPost]
public async Task<IActionResult> Create(Person person) 
{
  ValidationResult result = await _validator.ValidateAsync(person);

  if (!result.IsValid) 
  {
    // Copy the validation results into ModelState.
    // ASP.NET uses the ModelState collection to populate 
    // error messages in the View.
    result.AddToModelState(this.ModelState);
    // re-render the view when validation failed.
    return View("Create", person);
  }

  _repository.Save(person); //Save the person to the database, or some other logic

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

来源:https://docs.fluidation.net/en/latest/aspnet.html

© www.soinside.com 2019 - 2024. All rights reserved.