Reputation: 2484
I am trying to pass data to a WebAPI route, but it is not binding - the parameter received is always null.
On the frontend, I have an array of jobs, similar to this:
const jobs = [{Id: 1, Name: 'First'}, {Id: 2, Name: 'Second'}]
I am trying to pass this array to the backend, using a post request:
axios.post('jobs/insert', jobs, {
headers: { 'Content-Type': 'application/json' }
})
This is the resulting raw request:
POST /api/job/insert HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 51
Accept: application/json
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
DNT: 1
Content-Type: application/json
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,fr;q=0.
[{"Id":1,"Name":"First"},{"Id":2,"Name":"Second"}]
On the backend side, I have this method:
[HttpPost]
[Route("insert")]
public IActionResult InsertJob([FromBody] List<dto.Job> jobs)
{
return this.Ok(new { data = jobs });
}
The method is called correctly, but jobs is not binding correctly - it is always null.
This is the dto.Job model:
namespace Scheduling.Models.DTO
{
public class Job
{
public int Id { get; set; }
public string Name { get; set; }
}
}
I tried using List<dto.Job>
, dto.Job[]
, IEnumerable<dto.Job>
. I also tried removing [FromBody]
, or posting an object {'': jobs}
instead of an array (as suggested on other websites). Nothing seems to work, for some reason the data received is always null.
Am I doing something incorrectly?
Upvotes: 0
Views: 2258
Reputation: 16846
If you look at the request body, the array is not json stringified
This
[{"Id":1,"Name":"First"},{"Id":2,"Name":"Second"}]
Should be
"[{"Id":1,"Name":"First"},{"Id":2,"Name":"Second"}]"
In the axios request, try and stringify the object before sending it
axios.post('jobs/insert', JSON.stringify(jobs), {
headers: { 'Content-Type': 'application/json' }
})
Upvotes: 1