I have a controller method with array of integers input, which must not be null or more than 10 elements size. To validate input I 've made a class:
public class TestForm
{
    [Required]
    [MaxLength(10)]
    public long[] feedIds { get; set; }
}
And controller method:
[HttpPost]
public async Task<IActionResult> DoSomeJob(TestForm form)
{
    //Do some job
}
According to MSDN, System.ComponentModel.DataAnnotations.MaxLength can be used for array, but there is no validation, it gets null and array of any size. What am I doing wrong?
Here is what we use in one of our projects:
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;
    }
}
On a property like the following:
public class CreateUserApiRequest : ApiRequest {
    [DataMember]
    [Length(128)]
    [Description("クライアントキー")]
    public byte[] clientKey { get; set; }
    ....
                        The MaxLength atribute works fine. The problem was in action filter. Here is the code:
services.AddMvc(options =>
        {
            options.Filters.Add(new MyValidationFilterAttribute());
            //Some other code
        }
public class MyValidationFilterAttribute: IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext context)
    {
    }
    public void OnActionExecuting(ActionExecutingContext context)
    {
        if (context.ModelState.IsValid)
            return;
        if (!RequestRecognizingUtils.IsMobileAppRequest(context.HttpContext.Request))
            return; //Here all validation results are ignored
    }
}
In OnActionExecuting method validation errors were ignored
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With