Post的ServiceStack验证规则集不起作用

时间:2014-02-25 09:59:54

标签: validation servicestack

我使用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.IsValidtrue的方式?

1 个答案:

答案 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?
}