使用Fluent验证8和Asp.Net Core 2.2,我有:
public class ModelValidator : AbstractValidator<Model> {
public ModelValidator() {
RuleFor(x => x.File)
.Must(x => x.Length <= 40960).WithMessage("Max size of 40 Kb");
}
}
模型如下:
public class Model {
public IFormFile File { get; set; }
}
验证文件长度后,我需要执行以下操作:
将文件内容解析为我执行的FileParsedModel
FileParsedModel fileParsedModel = parser.ParseFile(Model.File);
然后验证FileParsedModel ...也许使用FileParsedModelValidator?
我应该在ModelValidator中注入FileParsedModelValidator吗?
我的想法是:
public class ModelValidator : AbstractValidator<Model> {
public ModelValidator(IValidator<FileParsedModel> validator) {
RuleFor(x => x.File)
.Must(x => x.Length <= 40960).WithMessage("Max size of 40 Kb")
.DependentRules(() => {
RuleFor(x => x.File).Custom((x, context) => {
FileParsedModel fileParsedModel = parser.ParseFile(x);
ValidationResult result = validator.Validate(fileParsedModel);
// Add failures to context
context.AddFailure("My error message");
});
});
}
}
有人能有更好的选择吗?