在API请求上执行验证时,资源结构可以完全嵌套:
public class NewAccountRequest
{
public AccountInfo Account { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
public class AccountInfo
{
public string Email { get; set; }
public string ImageUrl { get; set; }
public PersonalDetails PersonalDetails { get; set; }
}
public class PersonalDetails
{
public string GivenName { get; set; }
public string FamilyName { get; set;}
}
当用户将此信息发送给我的控制器时,我想使用FluentValidation对其进行验证,以确保满足所有前提条件。在响应中,我想返回错误信息以包括验证失败的元素的完整路径。
如果我为每个对象类型创建验证器,则验证错误中返回的值仅包含属性名称:
public class NewAccountRequestValidator : AbstractValidator<NewAccountRequest>
{
public NewAccountRequestValidator()
{
RuleFor(request => request.Account)
.SetValidator(new AccountInfoValidator())
.NotNull();
RuleFor(request => request.Username)
.NotNull();
RuleFor(request => request.Password)
.NotNull();
}
}
public class AccountInfoValidator : AbstractValidator<AccountInfo>
{
public AccountInfoValidator()
{
RuleFor(account => account.Email)
.NotNull();
}
}
如果帐户信息未指定电子邮件地址,则会使用&#34;电子邮件&#34;作为财产名称。我想返回&#34; Account.Email&#34;。
如果我停止使用嵌套验证器,并指定根对象验证器中所有属性的完整路径,则结果将以&#34; Account Email&#34;我可以将其转换为我想要的API的驼峰版本。我在使用嵌套验证器时也会喜欢这种行为,所以我没有为我的请求对象提供一个巨大的验证器类。