Post (React, C# ASP.NET Core) always returning null

42 Views Asked by At

I need send a int to a C# server (POST) and then return Json. On server (C#) always comes zero. In JS browser console all right (not null/zero). It's an http 500 error:

Failed to load resource: the server responded with a status of 500

Code:

const CallNextTextFromChoice = (nextChoiceID) => {
        axios.post('https://localhost:7252/Main/NextTextFromChoice', { nextChoiceID: nextChoiceID }, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                const data = response.data;
            })
            .catch(error => {
                console.log(nextChoiceID);
                console.error('Error:', error);
            });
    }

And C# code:

[HttpPost]
public IActionResult NextTextFromChoice(int nextChoiceID)
{
    var nextText = _dataBaseController.UpdateAllInfoWithChoice(nextChoiceID);

    return Json(nextText);
}

console.log(nextChoiceID) is working correctly and outputting the right integer.

I tried native indicate in C# Json data (with attribute [FromBody]), but result did not change. It always appears as null (or zero if using int). The message just doesn't get through

1

There are 1 best solutions below

1
Peppermintology On BEST ANSWER

The binding between the incoming request and method is not working as you expect. Change your method to be more explicit about the incoming parameters. Note that I have defined a record to encapsulate the your request parameters.

[HttpPost]
public IActionResult NextTextFromChoice([FromBody] NextChoiceRequest request)
{
    var nextText = _dataBaseController.UpdateAllInfoWithChoice(request.Id);

    return Json(nextText);
}
public record NextChoiceRequest(int Id);

The [FromBody] isn't entirely necessary here as there is no other binding going on and .NET is smart enough to work out the binding. However, it can be benificial to be explicit regardless.