arame3333
arame3333

Reputation: 10223

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

Upvotes: 5

Views: 1874

Answers (2)

Nkosi
Nkosi

Reputation: 247571

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.

Upvotes: 11

Lukasz Mk
Lukasz Mk

Reputation: 7350

I think the problem is here: IEnumerable<int>[] - it's array of lists of ints?

It should be simple int[] (or it could be IEnumerable<int>).

Upvotes: 0

Related Questions