0
我想通過使用REST,WCF和JSON(所有這些技術都是新的)來讓我的應用程序工作。我有'GET'正常工作。這是'POST'引起我的問題。發送JSON對象到WCF Rest服務
正如您將在下面看到的,我使用JSON.stringify'打包'我的JSON,然後將POST發送到REST資源。但是,當對象到達處理請求的WCF方法時,該對象始終爲空。
下面是代碼:
$(document).ready(function() {
var input = {
Customer: {
customerId: "1",
firstname: "luke",
lastname: "sayaw",
email: "[email protected]",
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)'的輸出是什麼? – 2013-04-09 05:27:18
不應該指定RequestFormat嗎? 'RequestFormat = WebMessageFormat.Json' – publicgk 2013-04-09 05:27:45
JSON.stringify的輸出是json格式的Customer數據。 – luke 2013-04-09 05:50:37