Checking the size of an array in C #
I have a controller method with an array of integers input, which must not be of size zero or more than 10 elements. To validate input, I created a class:
public class TestForm
{
[Required]
[MaxLength(10)]
public long[] feedIds { get; set; }
}
And the controller method:
[HttpPost]
public async Task<IActionResult> DoSomeJob(TestForm form)
{
//Do some job
}
According to MSDN , System.ComponentModel.DataAnnotations.MaxLength
can be used for an array, but no validation, it gets null and an array of any size. What am I doing wrong?
source to share
Here's 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;
}
}
For a property similar to the following:
public class CreateUserApiRequest : ApiRequest {
[DataMember]
[Length(128)]
[Description("γ―γ©γ€γ’γ³γγγΌ")]
public byte[] clientKey { get; set; }
....
source to share
MaxLength attribute works fine. The problem was filtering actions. 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
}
}
Validation errors were ignored in the OnActionExecuting validator method
source to share
If your property is feedIds
to be an array, then extending your property to do some validation like below should do the trick:
public class TestForm
{
private long[] _feedIds;
public long[] feedIds
{
get
{
if (_feedIds == null) _feedIds = new long[0];
return _feedIds;
}
set
{
if (value == null) throw new ArgumentNullException(nameof(value));
if (value.Length > 10) throw new ArgumentOutOfRangeException(nameof(value), "Max length of array is 10.");
_feedIds = value;
}
}
}
Koda
source to share