Web API中的手动模型验证

时间:2014-08-12 17:58:51

标签: c# .net asp.net-web-api

Web API附带了模型验证支持:ApiController.ModelState提供了一种快速,轻松的方式来查看输入有什么问题。有没有办法为任何随机对象获得类似的ModelStateDictionary?我知道Validator类,但是看看Web API的内部结构似乎比它更多。

1 个答案:

答案 0 :(得分:0)

我已将FluentValidation用于通用目的验证。它与ASP.NET MVC,WebAPI,WinForms等集成。

我可能已经习惯了,但我记得当我第一次使用它时它的API看起来非常简单。

我认为您可以使用它来获取验证结果,如果您真的需要使用它,请将它们转换为ModelStateDictionary

例如,这是您实现验证规则的方式:

public class CustomerValidator: AbstractValidator<Customer> {
  public CustomerValidator() {
    RuleFor(customer => customer.Surname).NotEmpty();
    RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
    RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
    RuleFor(customer => customer.Address).Length(20, 250);
    RuleFor(customer => customer.Postcode).Must(BeAValidPostcode)
                                          .WithMessage("Please specify a valid postcode");
  }

  private bool BeAValidPostcode(string postcode) {
    // custom postcode validating logic goes here
  }
}

这就是你执行实际验证的方式:

Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);

bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;