0

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?

2
  • Is the dto.Job from the Scheduling.Models.DTO namespace? Commented Feb 5, 2019 at 18:38
  • Yes, I have using dto = Scheduling.Models.DTO; in the controller Commented Feb 5, 2019 at 18:40

1 Answer 1

1

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' }
})
Sign up to request clarification or add additional context in comments.

2 Comments

The exact same data is posted with or without JSON.strignify (this seems to be a quirk of axios). I tried forcing the body to be a string: '"' + JSON.stringify(jobs) + '"', but still no luck
@Stratsys Great! It worked for me. However, I'm wondering why we should send string to a WebApi. I'd appreciate it if you could give me a reference to learn the reasoning behind that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.