Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array size validation in C#

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?

like image 893
AlexK Avatar asked Jul 27 '17 07:07

AlexK


2 Answers

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; }
    ....
like image 198
Hasan Emrah Süngü Avatar answered Nov 14 '22 02:11

Hasan Emrah Süngü


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

like image 27
AlexK Avatar answered Nov 14 '22 03:11

AlexK