我使用ServiceStack
构建一个Web服务,
这是我的validator
代码:
public class AccountValidator : AbstractValidator<AccountModel>
{
public AccountValidator()
{
//only for post
RuleSet(ServiceStack.ApplyTo.Post, () =>
{
RuleFor(s => s.Password).Length(30);
});
}
}
服务代码
public object Post(Account req) {
AccountModel model = req.ConvertTo<AccountModel>();
var result = this.Validator.Validate(model);
if (result.IsValid)
{
//is aways true
}
throw result.ToException();
}
Account.Password是“abc”,result.IsValid
是true
的方式?
答案 0 :(得分:2)
结果始终为true
,因为验证程序中的ApplyTo.Post
条件仅适用于在请求DTO 上验证的规则。 ApplyTo
条件不适用于手动调用的FluentValidation。请参阅Validation Documentation。
但鉴于您要将Account
转换为AccountModel
,您可以使用ValidationFeature
插件检查Account
的验证,然后再将其转换为AccountModel
}}
因此:
public class AccountValidator : AbstractValidator<Account>
{
public AccountValidator()
{
RuleSet(ApplyTo.Post, () => RuleFor(s => s.Password).Length(30));
}
}
// Account will be validated on POST
public object Post(Account req)
{
// Account is valid coming into the request
AccountModel model = req.ConvertTo<AccountModel>();
// Is it not safe to assume the model is valid, because Account is valid?
}