我无法让 FluentValidation 处理一组对象。我的 Controller POST 操作采用如下所示的 IEnumerable 对象。当我发布到采用单个 EventInputDto
且格式不正确的 Url
属性的操作时,我的验证成功进行。当我发布到 EventInputDto
集合时,它不起作用并且不进行验证。
如果我使用常规 MVC 属性(即 required/email),它们可以处理集合以及单个对象。我如何让它与 FluentValidation 一起使用?我没有使用内部集合,所以我不确定为什么它不能按预期工作。
public async Task<IActionResult> CreateEventCollection([FromBody] IEnumerable<EventInputDto> events)
{
if (!ModelState.IsValid)
{
return UnprocessableEntity(ModelState); //does not work
}
}
我的验证器是使用泛型设置的,因为我使用单独的模型进行输入和更新。
public class EventManipulationValidator<T> : AbstractValidator<T> where T : EventManipulationDto
{
public EventManipulationValidator()
{
RuleFor(manipulationDto => manipulationDto.Title).NotNull().WithMessage("Title cannot be blank")
.Length(1, 50);
RuleFor(manipulationDto => manipulationDto.Message).NotNull().WithMessage("Message cannot be blank")
.Length(1, 1000);
RuleFor(manipulationDto => manipulationDto.ScheduledTime).NotNull().WithMessage("Scheduled Time cannot be blank");
RuleFor(inputDto => inputDto.Url).Matches(@"https://.*windows\.net.*").WithMessage("The url must be valid and stored on Azure");
}
}
由于我的 CreateEventCollection 操作采用 EventInputDto 的 IEnumerable,我的 EventInputDto 验证器设置如下:
public class EventInputValidator : EventManipulationValidator<EventInputDto>
{
public EventInputValidator()
{
//all property validators are inherited from EventManipulationValidator
}
}
public class EventInputCollectionValidator : AbstractValidator<IEnumerable<EventInputDto>>
{
public EventInputCollectionValidator()
{
RuleForEach(p => p).SetValidator(new EventManipulationValidator<EventInputDto>());
}
}
以下是我的模型供引用:
EventManipulationDto
public abstract class EventManipulationDto
{
public string Title { get; set; }
public string Message { get; set; }
public string Url { get; set; }
public DateTime? ScheduledTime { get; set; }
}
EventInputDto
public class EventInputDto : EventManipulationDto
{
//all properties inherited from base class
}
最佳答案
在查看项目 GitHub 上的打开/关闭问题列表后,似乎并不是我的所有方法都是必需的。不需要我的 EventInputCollectionValidator。 FluentValidation 不再需要像我上面定义的那样显式定义 IEnumerable 验证器。
定义一个基本的 AbstractValidator 或在我的例子中是一个从父类继承的验证器就足够了。
让它工作所需的唯一更改是在注册 fluentvalidation 时在我的 startup.cs 中。我需要显式添加 ImplicitlyValidateChildProperties = true
。没有意识到这是必需的,因为我认为这是为了验证子属性集合而不是父集合对象。现在完美运行。
.AddFluentValidation(fv => {
fv.RunDefaultMvcValidationAfterFluentValidationExecutes = true;
fv.RegisterValidatorsFromAssemblyContaining<Startup>();
fv.ImplicitlyValidateChildProperties = true;
});
关于c# - FluentValidation 不适用于外部模型对象的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53236279/