Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot send a collection of integers to a Web Core Api Post method, it is set to null

I want to send a collection of integers to a post method on a web core api.

The method is;

[HttpPost("open")]
public IActionResult OpenInspections([FromBody]IEnumerable<int> inspectionIds)
{
    return NoContent();
//...

This is just for testing, I put a break point on the return statement and the inspectionIds payload is null.

In Postman I have

enter image description here

EDIT: I have just removed the square brackets from the signature. I was trying both IEnumerable<int> and int[] but neither worked

like image 792
arame3333 Avatar asked Jun 23 '17 11:06

arame3333


1 Answers

It is null because what is posted and what is expected by the action do not match, so it does not bind the model when posted. Example data being sent has a string array ["11111111", "11111112"] and not int array [11111111, 11111112],

also IEnumerable<int>[] represents a collection of collections, like

{ "inspectionIds": [[11111111, 11111112], [11111111, 11111112]]}

To get the desired behavior either update action to expect the desired data type

[HttpPost("open")]
public IActionResult OpenInspections([FromBody]int[] inspectionIds) {
    //...
}

Making sure that the posted body also matches what is expected

[11111111, 11111112]

OR

consider using a concrete model as the posted data in the provided question is a JSON object.

public class Inspection {
    public int[] inspectionIds { get; set; }
}

And update the action accordingly

[HttpPost("open")]
public IActionResult OpenInspections([FromBody]Inspection model) {
    int[] inspectionIds = model.inspectionIds;
   //...
}

the model would also have to match the expected data being posted.

{ "inspectionIds": [11111111, 11111112] }

Note that if the desired ids are suppose to be int then do not wrap them in quotes.

like image 180
Nkosi Avatar answered Oct 30 '22 01:10

Nkosi