自定义验证未触发

时间:2021-04-30 11:01:30

标签: c# fluentvalidation

FluentValidation 8.5 版 ASP.NET 版本 .NET Core 2.2

总结 验证没有触发,我错过了什么吗?

// 用法

public class Validator : AbstractValidator<Command>
{
    public Validator()
    {
        RuleFor(x => x.File).SetValidator(new UploadValidator());
    }
}

// 这是我的自定义验证器。

public class UploadValidator : AbstractValidator<IFormFile>
{
    public UploadValidator()
    {
        RuleFor(m => m).NotNull()
            .WithMessage("File to upload is missing");
        
        RuleFor(m => m.Length).GreaterThan(0)
            .WithMessage("File size is too small");

        // 157286400 = 150mb;
        RuleFor(x => x.Length).NotNull().LessThanOrEqualTo(157286400)
            .WithMessage("File size is larger than allowed (150 Mb)");
    }
}

1 个答案:

答案 0 :(得分:0)

UploadValidator 类继承自 AbstractValidator<IFormFile>。按照命名约定,IFormFile 是一个接口。看起来 FluentValidation 不支持验证接口,只支持具体的类。

<块引用>

要为特定对象定义一组验证规则,您需要创建一个继承自 AbstractValidator<T> 的类,其中 T类的类型您希望验证。

来源:Creating your first validator

由于您尚未发布视图模型的代码,因此我无法推荐特定的修复程序。更一般地说,如果您有多种文件上传,请尽可能使用具体类的层次结构来验证对象。您仍然可以使用接口来处理它们,但似乎 FluentValidation 需要类。