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.
2
Answers
If you send it in JSON, you should use
[FromBody]
attribute:[FromForm]
is used, when object is sent as a form-dataIt looks like you sent a non-form body to the controller before. Now you are sending it without setting content type.
Add another header:
You should be able to send data without stringify with axios. Try setting [FromBody] again and the request below