【发布时间】:2018-11-11 01:48:33
【问题描述】:
我无法让 FluentValidation 处理对象集合。我的控制器 POST 操作接受一个 IEnumerable 对象,如下所示。当我发布到采用单个EventInputDto 的操作时,Url 属性格式不正确,我的验证成功进行。当我发布到EventInputDto 的集合时,它不起作用并且没有验证。
如果我使用常规 MVC 属性(即必需/电子邮件),它们可以与集合以及单个对象一起使用。如何让它与 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
}
【问题讨论】:
标签: c# asp.net asp.net-mvc fluentvalidation