Issues while making a POST to a Web API from JQuer

2019-06-26 18:01发布

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...

2条回答
我只想做你的唯一
2楼-- · 2019-06-26 18:47

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.

查看更多
Anthone
3楼-- · 2019-06-26 18:48

There might be an issue with binding the value to the response sent to the server

try sending the 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 am assuming that your JSON.stringify(message) returns a string value

updated

 public HttpResponseMessage Post([ModelBinder]string package)

allowing package to bind from everywhere instead of just body did it for me.

查看更多
登录 后发表回答