如何用 Fluent Validation 替换默认的 web api 模型验证

How to replace the default web api model validation with Fluent Validation

[Validator(typeof(ProductDetailsRequestDTO))]
    public class ProductDetailsRequestDTO
    {
        public int ArticleGroup { get; set; }
        public DateTime ProducedAt { get; set; }
    }

public class ProductDetailsRequestDTOValidator : AbstractValidator<ProductDetailsRequestDTO>
    {
        public ProductDetailsRequestDTOValidator()
        {
            RuleFor(r => r.ArticleGroup).NotEmpty().WithMessage("custom message");
            RuleFor(r => r.ProducedAt).NotEmpty().WithMessage("custom message");
        }
    }

 // FluentValidation setup 
        config.Services.Add(typeof(System.Web.Http.Validation.ModelValidatorProvider), new FluentValidationModelValidatorProvider());

fluentvalidation 从哪里知道我创建的验证器以及为什么我的模型总是正确的?

这只是一个错字。您的模型装饰有错误的类型名称。而不是像这样装饰它:

[Validator(typeof(ProductDetailsRequestDTO))]
public class ProductDetailsRequestDTO
{
    public int ArticleGroup { get; set; }
    public DateTime ProducedAt { get; set; }
}

用你的验证器类型装饰它:

[Validator(typeof(ProductDetailsRequestDTOValidator))]
public class ProductDetailsRequestDTO
{
    public int ArticleGroup { get; set; }
    public DateTime ProducedAt { get; set; }
}