Problems creating POST for web API from jQuery

I have a web api with the following POST method

public HttpResponseMessage Post([FromBody]string package) 

I have a console application that uses HttpCLient without problems. When I try to make a call using jQuery , I get null in the package variable.

This is the code that 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 variable "message" is a complex model containing two properties.

What can i do wrong?

I would be grateful for your help ...

+4
source share
2 answers

I managed to find a solution in another article: Calling Web Api POST always gets a null value from jQuery .

I had to change my code as follows:

The line that reads: data: JSON.stringify (message) has been changed to: data: JSON.stringify ('=' + message),.

I went over to the post API method and added the following line of code:

package = package.Replace ("=", "");

to remove the '=' that was added to the jQuery post.

+1
source

There might be a problem associating the value with the response sent to the server

try sending data as

 $.ajax({ url: 'http://localhost:8081/api/Package/', type: 'POST', data: { package : JSON.stringify(message) } datatype: 'json', success: function (data) { alert(data.length); }, error: function (xhr, ajaxOptions, thrownError) { alert('Status: '+xhr.status+', Error Thrown: '+thrownError); } }); 

I assume your JSON.stringify(message) returns a string value

updated

  public HttpResponseMessage Post([ModelBinder]string package) 

letting the package communicate from the outside, and not just the body did it for me.

0
source

All Articles