Web API 附带内置的模型验证支持:ApiController.ModelState
提供了一种快速、轻松的方式来查看您的输入有什么问题。有没有办法为任何随机对象获取类似的 ModelStateDictionary
?我知道 Validator
类,但看看 Web API 的内部结构,它似乎涉及的内容远不止于此。
最佳答案
我用过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;
关于c# - Web API 中的手动模型验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25271047/