[英]Require not null collection elements in when validating model in aspnet core
I have example mode class:我有示例模式 class:
public class Data
{
[Required]
[MinLength(1)]
public List<Foo> Foos{ get; set; }
}
which is passed to controller:传递给 controller:
[ApiController]
public class FooController : ControllerBase
{
public async Task<IActionResult> Post([FromBody] Data data)
{
// Do stuff
}
}
I have nullable annotations enabled in my project configuration.我在我的项目配置中启用了可为空的注释。
How can I force model validator to reject request with null foos array?如何强制 model 验证器拒绝使用 null foos 数组的请求? For example following request is accepted by controller:
例如,controller 接受以下请求:
{
foos: [null]
}
I would like such request to return bad request status code.我希望这样的请求返回错误的请求状态代码。
When using Data Annotations the child classes are not validated.使用数据注释时,子类不会被验证。 I recommend Fluent Validation for the use case presented.
我建议对所展示的用例进行Fluent Validation 。
The use is simple, just define a rule使用很简单,只要定义一个规则
public class DataValidator : AbstractValidator<Data>
{
public DataValidator()
{
// RuleFor(r => r.Foos).NotEmpty(); // <-- not needed as Nullable Annotations are enabled
RuleForEach(r => r.Foos).NotNull();
}
}
And register FluentValidation
in configure services method并在配置服务方法中注册
FluentValidation
services.AddControllers()
.AddFluentValidation(configuration => configuration.RegisterValidatorsFromAssemblyContaining<Startup>());
You could custom ValidationAttribute to custom the rule:您可以自定义 ValidationAttribute 来自定义规则:
Custom ValidationAttribute:自定义验证属性:
public class ValidArray : ValidationAttribute
{
protected override ValidationResult
IsValid(object value, ValidationContext validationContext)
{
var model = (Data)validationContext.ObjectInstance;
if(Extension.IsNullOrEmpty<Foo>(model.Foos))
{
return new ValidationResult
("Array cannot be null");
}
else
{
return ValidationResult.Success;
}
}
}
Custom IsNullOrEmpty
:自定义
IsNullOrEmpty
:
public static class Extension
{
public static bool IsNullOrEmpty<T>(List<T> array) where T : class
{
if (array == null || array.Count == 0)
return true;
else
return array.All(item => item == null);
}
}
Model: Model:
public class Data
{
//[Required]
[MinLength(1)]
[ValidArray]
public List<Foo> Foos { get; set; }
}
public class Foo
{
public int Id { get; set; }
public int Count { get; set; }
}
Result:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.