您对如何使 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());
}
});
}
}
您需要使用
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 的验证管道不是异步的。