C# FluentValidation不处理外部模型对象的集合
我在让FluentValidation处理对象集合时遇到问题。我的控制器POST操作接收一个IEnumerable对象,如下所示。当我使用格式不正确的C# FluentValidation不处理外部模型对象的集合,c#,asp.net,asp.net-mvc,fluentvalidation,C#,Asp.net,Asp.net Mvc,Fluentvalidation,我在让FluentValidation处理对象集合时遇到问题。我的控制器POST操作接收一个IEnumerable对象,如下所示。当我使用格式不正确的Url属性发布到将单个EventInputDto转换为的操作时,我的验证成功发生。当我将事件输入的集合发布到时,它不起作用,也不进行验证 如果我使用常规的MVC属性(即required/email),它们可以处理集合和单个对象。我如何让它与FluentValidation一起工作?我不使用内部集合,所以我不确定它为什么不能按预期工作 public
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 abstract class EventManipulationDto
{
public string Title { get; set; }
public string Message { get; set; }
public string Url { get; set; }
public DateTime? ScheduledTime { get; set; }
}
public class EventInputDto : EventManipulationDto
{
//all properties inherited from base class
}
在浏览了GitHub项目的开放/关闭问题列表之后,似乎并不需要我所有的方法。不需要我的“EventInputCollectionValidator”。FluentValidation不再需要像我上面定义的那样显式定义IEnumerable验证器
定义一个基本的AbstractValidator,或者在我的例子中,定义一个继承自父类的验证器就足够了
注册fluentvalidation时,唯一需要做的更改是在my startup.cs中。我需要显式添加隐式ValidateChildProperties=true
。没有意识到这是必需的,因为我认为这是为了验证子属性集合而不是父集合对象。现在效果很好
.AddFluentValidation(fv => {
fv.RunDefaultMvcValidationAfterFluentValidationExecutes = true;
fv.RegisterValidatorsFromAssemblyContaining<Startup>();
fv.ImplicitlyValidateChildProperties = true;
});
.AddFluentValidation(fv=>{
fv.RunDefaultMvcValidationAfterFluentValidationExecutes=true;
fv.RegisterValidatorsFromAssemblyContaining();
fv.ImplicitlyValidateChildProperties=true;
});
public class EventInputDto : EventManipulationDto
{
//all properties inherited from base class
}
.AddFluentValidation(fv => {
fv.RunDefaultMvcValidationAfterFluentValidationExecutes = true;
fv.RegisterValidatorsFromAssemblyContaining<Startup>();
fv.ImplicitlyValidateChildProperties = true;
});