Ale*_*exK 3 c# validation asp.net-core-mvc
我有一个带有整数输入数组的控制器方法,它不能为null或大于10个元素.为了验证输入,我做了一个课程:
public class TestForm
{
[Required]
[MaxLength(10)]
public long[] feedIds { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和控制器方法:
[HttpPost]
public async Task<IActionResult> DoSomeJob(TestForm form)
{
//Do some job
}
Run Code Online (Sandbox Code Playgroud)
根据MSDN,System.ComponentModel.DataAnnotations.MaxLength可以用于数组,但是没有验证,它获取null和任何大小的数组.我究竟做错了什么?
以下是我们在其中一个项目中使用的内容:
public class LengthAttribute : ValidationAttribute {
readonly int length;
public LengthAttribute(int length) {
this.length = length;
}
public override bool IsValid(object value) {
if (value is ICollection == false) { return false; }
return ((ICollection)value).Count == length;
}
}
Run Code Online (Sandbox Code Playgroud)
在如下属性上:
public class CreateUserApiRequest : ApiRequest {
[DataMember]
[Length(128)]
[Description("????????")]
public byte[] clientKey { get; set; }
....
Run Code Online (Sandbox Code Playgroud)