【发布时间】:2013-04-09 05:22:44
【问题描述】:
我正在尝试通过使用 REST、WCF 和 JSON(所有这些技术的新手)让我的应用程序正常工作。我的“GET”工作正常。导致我出现问题的是“POST”。
正如您将在下面看到的,我使用 JSON.stringify“打包”我的 JSON,然后将 POST 发送到 REST 资源。但是,当对象到达处理请求的 WCF 方法时,该对象始终为空。
代码如下:
$(document).ready(function () {
var input = {
Customer: {
customerId: "1",
firstname: "luke",
lastname: "sayaw",
email: "lumsayaw@gmail.com",
mobile: "0433395106",
state: "QLD"
}
};
$.ajax({
url: 'http://local.rest/restservice.svc/getcustomer',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(input),
dataType: 'json',
type: 'POST',
async: true,
success: function (data, success, xhr) {
alert('Group saved - ' + data);
alert('first name: ' + data.firstname);
},
error: function (xhr, status, error) {
alert('Error! - ' + xhr.status + ' ' + error);
}
});
});
以及服务器端代码:
namespace RestService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "RestService" in code, svc and config file together.
public class RestService : IRestService
{
public string getcustomer(Customer Customer)
{
string id = Customer.customerId ;
return new JavaScriptSerializer ().Serialize (Customer );
}
}
[DataContract ]
public class Customer
{
public string customerId {get;set;}
public string firstname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string mobile { get; set; }
public string state { get; set; }
}
}
namespace RestService
{
[ServiceContract]
public interface IRestService
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/getcustomer")]
[return: MessageParameter(Name = "Customer")]
string getcustomer(Customer Customer);
}
}
非常感谢
【问题讨论】:
-
JSON.stringify(input)的输出是什么? -
您不应该也指定 RequestFormat 吗?
RequestFormat = WebMessageFormat.Json -
JSON.stringify 的输出是 json 格式的客户数据..
-
公共字符串 getcustomer(Customer Customer) 总是返回 null。
-
我已经正确发布了json格式的客户数据..但是服务器端方法返回空对象