简体   繁体   English

方法 MustAsync() 与 WhenAsync() FluentValidation 之间的差异

[英]Differences between methods MustAsync() vs WhenAsync() FluentValidation

I implement an API with .net 5 and I use the NuGet FluentValidation.我用 .net 5 实现了 API 并使用 NuGet FluentValidation。 I try to understand what is the difference between the two methods我试图了解这两种方法有什么区别

MustAsync()必须异步()

WhenAsync()何时异步()

and when must I use each of them.我什么时候必须使用它们。 It is better if you can provide an example.如果你能提供一个例子就更好了。

The WhenAsync() method: Specifies an asynchronous condition limiting when the validator should run. WhenAsync()方法:指定一个异步条件限制验证器何时运行。 The validator will only be executed if the result of the lambda returns true.只有当 lambda 的结果返回 true 时,才会执行验证器。

The MustAsync() method: Defines an asynchronous predicate validator on the current rule builder using a lambda expression to specify the predicate. MustAsync()方法:在当前规则构建器上定义一个异步谓词验证器,使用 lambda 表达式指定谓词。 Validation will fail if the specified lambda returns false.如果指定的 lambda 返回 false,则验证将失败。 Validation will succeed if the specified lambda returns true.如果指定的 lambda 返回 true,则验证将成功。

You could go to the method definition and check the used of these methods.您可以 go 到方法定义并检查这些方法的使用情况。

Both of the above methods are used to define asynchronous rules, for example, the following code will check if a user ID already exists:以上两种方法都是用来定义异步规则的,例如下面的代码会检查一个用户ID是否已经存在:

public class CustomerValidator : AbstractValidator<Customer> {
  SomeExternalWebApiClient _client;

  public CustomerValidator(SomeExternalWebApiClient client) {
    _client = client;

    RuleFor(x => x.Id).MustAsync(async (id, cancellation) => {
      bool exists = await _client.IdExists(id);
      return !exists;
    }).WithMessage("ID Must be unique");
  }
}

Then, invoke the validator by calling ValidateAsync method.然后,通过调用ValidateAsync方法调用验证器。

var validator = new CustomerValidator(new SomeExternalWebApiClient());
var result = await validator.ValidateAsync(customer);

More detail information, refer the following articles:更多详细信息,请参阅以下文章:

Asynchronous Validation异步验证

FluentValidation流利验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM