My website makes this request:
const httpLink = 'https://www.myServer.com' + '/api/DBCom/saveInformation';
var postAxios = axios({
method: 'post',
url: httpLink,
params: {tableName: tableName},
headers: {'Content-Type': 'application/json' },
data: rowInfo
}
).then(function (response) {
console.log(response);
// alert(response);
// answer = true;
})
.catch(function (error) {
console.log(error);
alert('Error' + error.response.data);
answer = false;
// location.replace(getServerInfo());
});
My C# .NET 7.0 controller looks like this:
[Route("api/[Controller]")]
[ApiController]
public class DBComController : ControllerBase
{
[HttpGet("Index")]
public string Index()
{
return "hello all";
}
[HttpPost("saveInformation")]
public string saveInformation([FromBody] string value)
{
Console.WriteLine(value);
return "hello from post";
}
}
I know the controller is being found as the Index
get call works. However, for the POST I am getting an error:
User.js:265
POST https: ############/api/DBCom/saveInformation 400 (Bad Request)
dispatchXhrRequest @ xhr.js:256
xhr @ xhr.js:49
dispatchRequest @ dispatchRequest.js:51
request @ Axios.js:146
wrap @ bind.js:5
User.onBlurOfTextbox @ User.js:265
onBlur @ User.js:371
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Show 20 more frames
Show less
User.js:278 AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
What am I missing?
2
Answers
The solution I found is that it is necessary to use System.Text.Json and instead of
Use
or something similar as
Ref: ASP.NET Core 3.0 [FromBody] string content returns "The JSON value could not be converted to System.String."
As marc_s said, to post JSON data to the server, you need to provide the JSON data in the HTTP POST request body and pass the "Content-Type: application/json" request header. The Content-Type request header specifies the media type for the resource in the body.
Add the header like:
result: