4

我有一个带有以下 POST 方法的 web api

public HttpResponseMessage Post([FromBody]string package)

我有一个使用HttpCLient没有问题的控制台应用程序。当我尝试通过 拨打电话时jQuery,我得到null了包变量。

这是我现在拥有的代码:

$.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);

        }
    });

“消息”变量是一个包含两个属性的复杂模型。

我可能做错了什么?

我会感谢你的帮助...

4

1 回答 1

0

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.

于 2013-02-12T03:26:11.210 回答