Home > Back-end >  .Net Core API not receiving object in Post request
.Net Core API not receiving object in Post request

Time:11-04

I have the following class / controller in my .Net Core API:

public class Tester
{
    public string Word1 { get; set; }
    public string Word2 { get; set; }
    public string Word3 { get; set; }
}

[Route("/users")]
[ApiController]
public class UserController : AController<User, IUserRepository>
{

    [Authorize]
    [HttpPost("Test1")]
    public async Task<IActionResult> Test1([FromForm] Tester test)
    {
        return Ok();
    }

}

And in my React front-end I have the following code to Post to the API using Axios:

const sendToServer = () => {        
    const test = {Word1: "abc", Word2: "def", Word3: "ghi"};

    axios
        .post(
            '<my server>', 
            JSON.stringify(test), 
            {headers: { Accept: 'application/json' }}
        )
        .then(result => {
            console.log(result.data);
        })
    ;
}

And, when I run the function, my API action does get hit, but the test object is always empty (all 3 Word values are null).

I've tried to update the Post request in various ways such as:

let data = new FormData();
data.append("tester", {Word1: "abc", Word2: "def", Word3: "ghi"});

axios
    .post(
        '<my server>', 
        data, 
        {headers: { Accept: 'application/json' }}
    )
    .then(result => {
        console.log(result.data);
    })
;

or

let data = new FormData();
data.append("tester", JSON.stringify({Word1: "abc", Word2: "def", Word3: "ghi"}));

But, every time, the test object doesn't get populated.

And, when I try and change the APi from FromForm to FromBody, it then never reaches the API and I get an error from the Axios post method:

Request Method: POST
Status Code: 415 
Remote Address: [::1]:5001
Referrer Policy: strict-origin-when-cross-origin

This is all very new to me, so I'm sure this is something stupid I am missing, but I have looked and can't find a solution that fixes this problem for me.

CodePudding user response:

It looks like you sent a non-form body to the controller before. Now you are sending it without setting content type.

Add another header:

'Content-Type' : 'application/json'

You should be able to send data without stringify with axios. Try setting [FromBody] again and the request below

const sendToServer = () => {
    const test = { Word1: "abc", Word2: "def", Word3: "ghi" };

    axios
        .post(
            '<my server>',
            test,
            { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }
        )
        .then(result => {
            console.log(result.data);
        });
}

CodePudding user response:

If you send it in JSON, you should use [FromBody] attribute:

   public async Task<IActionResult> Test1([FromBody] Tester test)

[FromForm] is used, when object is sent as a form-data

  • Related