How can I make the int [] parameter needed in the web api?

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

These operations are as follows:

[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 click this on http://localhost/api/SomeEntity/ByIds?ids=1&ids=2 , for example, you will get an array with 1 and 2, as you expected.

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

I suspect what happens when it recognizes it as one of the specified elements, cannot convert it, so it uses default(int) and puts it in an array that gives you an int array with a single value, value 0.

However, if you click on it http://localhost/api/SomeEntity/ByIds?ids=potato , you will get an invalid model state, and I will automatically handle this.

The question is: what is the approach to displaying an empty value for a query parameter for an empty array or a ModelState error (i.e., the same behavior as a potato if you send an empty value)? I think a model error would be preferable and more logical.

+5
source share
1 answer

The value of int is 0 because 0 is zero for the string. If you want your int to be null, use int?

Basically:

 int i = 0 

Is the integer equivalent

 string myString = null; 

And if you want your int to be null, use

 int? i = null; 

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

+1
source

Source: https://habr.com/ru/post/1232781/


All Articles