按条件设置 Fluent Validator

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

我正在尝试为“Address”设置验证器,具体取决于项目是否存在,但我想使用 RuleFor 和其他方便的方法,而不是使用“ValidationContext”手动记录每个错误,但似乎当我尝试通过“CustomAsync”来执行此操作时`,它只是被跳过,并且跳过了 `RequestAddressValidator` 的规则。

您对如何使 RequestAddressValidator 规则发挥作用有什么想法吗?

public class RequestModel
{
    public required string Id { get; init; }

    public Address? Address { get; init; }
}

public class Address
{
    public required string Line1 { get; init; }
    public required string Line2 { get; init; }
}

public class RequestAddressValidator: AbstractValidator<Address>
{
    public RequestAddressValidator()
    {
        RuleFor(x => x.Line1).NotEmpty();
        RuleFor(x => x.Line2).NotEmpty();
    }
}

public class RequestModelValidator: AbstractValidator<RequestModel>
{
    public RequestModelValidator(IApiClient apiClient)
    {
        RuleFor(x => x)
            .Custom((requestModel, context) =>
            {
                var item = apiClient.GetByIdAsync(requestModel.Id);

                if (item != null)
                {
                    RuleFor(x => x.Address).SetValidator(new RequestAddressValidator());
                }
            });
    }
}
c# asp.net validation .net-core fluentvalidation
1个回答
0
投票

您需要使用

CustomAsync
并等待
apiClient.GetByIdAsync
来电。

参见 异步验证

public class RequestModelValidator: AbstractValidator<RequestModel>
{
    public RequestModelValidator(IApiClient apiClient)
    {
        RuleFor(x => x)
            .CustomAsync(async (requestModel, context, cancellationToken) =>
            {
                var item = await apiClient.GetByIdAsync(requestModel.Id);

                if (item != null)
                {
                    RuleFor(x => x.Address).SetValidator(new RequestAddressValidator());
                }
            });
    }
}

还要注意该页面上的通知,尤其是有关 ASP.NET 自动验证的通知。

由于您将此问题标记为

ASP.NET
并且您正在使用异步验证,因此您需要使用 手动验证;自己调用验证器。

如果您的验证器包含异步验证器或异步条件,请务必在验证器上始终调用

ValidateAsync
,而不是
Validate
。如果调用 Validate,则会抛出异常。

在 ASP.NET 中使用自动验证时不应使用异步规则,因为 ASP.NET 的验证管道不是异步的。

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