Hel*_*123 5 c# asp.net asp.net-mvc fluentvalidation
我在让 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
}
}
Run Code Online (Sandbox Code Playgroud)
我的验证器是使用泛型设置的,因为我使用单独的模型进行输入和更新。
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");
}
}
Run Code Online (Sandbox Code Playgroud)
由于我的 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>());
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我的模型供参考:
事件操作Dto
public abstract class EventManipulationDto
{
public string Title { get; set; }
public string Message { get; set; }
public string Url { get; set; }
public DateTime? ScheduledTime { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
事件输入Dto
public class EventInputDto : EventManipulationDto
{
//all properties inherited from base class
}
Run Code Online (Sandbox Code Playgroud)
在查看了项目 GitHub 上的开放/已关闭问题列表后,似乎并不需要我的所有方法。不需要我的`EventInputCollectionValidator。FluentValidation 不再需要像我上面定义的那样显式定义 IEnumerable 验证器。
定义一个基本的 AbstractValidator 或在我的例子中定义一个从父类继承的验证器就足够了。
让它工作所需的唯一更改是在注册 FluentValidation 时在我的startup.cs中进行。我需要明确添加ImplicitlyValidateChildProperties = true. 没有意识到这是必需的,因为我认为这是为了验证子属性集合而不是父集合对象。现在工作完美。
.AddFluentValidation(fv => {
fv.RunDefaultMvcValidationAfterFluentValidationExecutes = true;
fv.RegisterValidatorsFromAssemblyContaining<Startup>();
fv.ImplicitlyValidateChildProperties = true;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2986 次 |
| 最近记录: |