Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an int[] parameter required in web api?

I have a bunch of operations on my api that are generic GetById and GetByIds that pull an entity out and return it via a formatter.

These operations look like this:

[HttpGet]
[Route("ByIds")]
public IHttpActionResult ByIds([FromUri]int[] ids)
{
    var items = _myContext.SomeEntity.Where(a => ids.Contains(a.ID)).ToList();
    return SomeFormatter(items);
}

If you hit this with http://localhost/api/SomeEntity/ByIds?ids=1&ids=2 for example, you get an array with 1 and 2 in as you'd expect.

If you hit this with http://localhost/api/SomeEntity/ByIds?ids= you might expect to get an empty array, but you get int[1] with a value of 0 in it.

I suspect what happens is it recognises it as one element specified, cannot convert it, so uses default(int) and puts that into the array, which gives you an int array with one value, the value of 0.

However if you hit it with http://localhost/api/SomeEntity/ByIds?ids=potato then you get an invalid modelstate and I automatically handle that.

The question is, what's a catch all approach of mapping an empty query parameter value to either an empty array or a ModelState error (i.e. the same behaviour as potato if you supply an empty value)? I think a modelstate error would be preferred and is more logical.

like image 274
NibblyPig Avatar asked Nov 10 '22 04:11

NibblyPig


1 Answers

The int value of 0 occurs because 0 is the same as null for a string. If you want your int to have a value of null use int?

Basicly:

int i = 0

Is the integer equivalent of

string myString = null;

And if you want your int to be null use:

int? i = null;

So what happens is the array wants at least one item, it will not assign a value to that one item. But since the default value of an integer is 0, it will get that value

like image 67
Teun Vos Avatar answered Nov 15 '22 07:11

Teun Vos