ServiceStack - FluentValidation

ServiceStack - FluentValidation

我对将 FluentValidation 与 ServiceStack 结合使用有疑问。

例如:

[Route("/customers/{Id}", "PUT")]
public class UpdateCustomer : IReturn<Customer>
{
    public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

[Route("/customers/{Id}", "DELETE")]
public class DeleteCustomer : IReturnVoid
{
    public int Id { get; set; }
}

public class Customer
{
    public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

当我更新客户信息时,我想验证所有参数,但例如删除它时,我只想确保 Id 是正整数。所以,FirstName、LastName 等等。在这种情况下我不关心其他所有内容。

如果我在 Customer class 上实施 FluentValidator,我是否必须为此将所有逻辑放在验证器中(以根据请求路由应用不同的规则)?或者有更优雅的方式来做到这一点?

验证器应该只在请求 DTO 上,例如:

public class UpdateCustomerValidator : AbstractValidator<UpdateCustomer>
{
    public UpdateCustomerValidator()
    {
        RuleFor(r => r.Id).GreaterThan(0);
        RuleFor(r => r.FirstName).NotEmpty();
        RuleFor(r => r.LastName).NotEmpty();
    }
}

DeleteCustomer 同样如此,例如:

public class DeleteCustomerValidator : AbstractValidator<DeleteCustomer>
{
    public DeleteCustomerValidator()
    {
        RuleFor(r => r.Id).GreaterThan(0);
    }
}

虽然为单个字段创建整个验证器可能有点矫枉过正,因此您可以改为只在您的服务中添加验证,例如:

public class CustomerServices : Service
{
    public void Any(DeleteCustomer request)
    {
        if (request.Id <= 0)
            throw new ArgumentException("Id Required", "Id")

        Db.DeleteById<Customer>(request.Id);
    }
}