I have a web api with the following POST Method
public HttpResponseMessage Post([FromBody]string package)
I have a console app that uses the HttpCLient
with no problems. When I try to make a call by means of jQuery
, I get null
on the package variable.
This is the code I have right now:
$.ajax({
url: 'http://localhost:8081/api/Package/',
type: 'POST',
data: JSON.stringify(message),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert(data.length);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Status: '+xhr.status+', Error Thrown: '+thrownError);
}
});
The "message" variable is a complex model containing two properties.
What could I be doing wrong?
I'll appreciate your help...
I was able to find a solution on another article here: Calling Web Api POST always receives null value from jQuery.
I had to modify my code the following way:
The line that reads: data: JSON.stringify(message), was changed to: data: JSON.stringify('='+message) , .
I went to the API post method and added the following line of code:
package = package.Replace("=", "");
in order to remove the '=' that was added on the JQuery post.
There might be an issue with binding the value to the response sent to the server
try sending the data as
I am assuming that your
JSON.stringify(message)
returns a string valueupdated
allowing package to bind from everywhere instead of just body did it for me.