ServiceStack - FluentValidation
本文关键字:FluentValidation ServiceStack | 更新日期: 2023-09-27 18:02:03
我有一个关于使用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等等其他的我都不关心
如果我在客户类上实现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);
}
}