C# 如何告诉FluentValidation不要检查请求中未包含字段的子字段的规则?
我使用的是FluentValidation 9.2.2版。 我收到以下信息:C# 如何告诉FluentValidation不要检查请求中未包含字段的子字段的规则?,c#,fluentvalidation,C#,Fluentvalidation,我使用的是FluentValidation 9.2.2版。 我收到以下信息: System.NullReferenceException:“对象引用未设置为对象的实例。” Json: {“地理信息”:{ “国家代码”:“英国”} 问题是,如果我发送这样的json: Json: {} (没有地理信息),我得到一个NullReferenceException,而我期望“GeographyInfo missing.Expected:GeoInfo类型的对象” 我认为FluentValidation会继
System.NullReferenceException:“对象引用未设置为对象的实例。”
Json:
{“地理信息”:{
“国家代码”:“英国”}
问题是,如果我发送这样的json:
Json:
{}
(没有地理信息),我得到一个NullReferenceException,而我期望“GeographyInfo missing.Expected:GeoInfo类型的对象”
我认为FluentValidation会继续进行并检查第二条规则:在字段x.Request.GeographyInfo.CountryCode上,但在本例中我们没有x.Request.GeographyInfo,因此进一步引用CountryCode没有意义
我如何告诉FluentValidation不要检查他没有找到的字段子字段的规则?(不包括在请求中)对于您的特定情况,您可以指示FluentAPI在第一次失败时跳过执行:
ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;
或者,您可以使用When方法首先检查对象是否为null:
When(x => x.Request.GeographyInfo != null, () => {
RuleFor(x => x.Request.GeographyInfo.CountryCode)
.NotEmpty()
.WithMessage("Field geographyInfo.CountryCode is missing. Expected: 3 digit code")
.WithErrorCode("13")
.WithName("countryCode");
});
非常感谢。RuleFor(x=>x.Request.GeographyInfo?.CountryCode)-我以前试过这个,但没用。我得到:“表达式树lambda可能不包含null传播运算符。”//有趣的是,CascadeMode.StopOnFirstFailure;有可能,我现在正在检查。我希望它不会干扰其他不相关的错误,例如,除了GeoInfo(主字段,而不是子字段)上的错误外,理想情况下还应显示完全不同字段上的错误。哦,是的,确实如此,但您可以在何时包装RuleFor,如本文所建议的-
When(x => x.Request.GeographyInfo != null, () => {
RuleFor(x => x.Request.GeographyInfo.CountryCode)
.NotEmpty()
.WithMessage("Field geographyInfo.CountryCode is missing. Expected: 3 digit code")
.WithErrorCode("13")
.WithName("countryCode");
});