0

我正在尝试通过使用 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);
}
}

非常感谢

4

1 回答 1

0

尝试:

[OperationContract, WebGet(UriTemplate = "/GetJson", BodyStyle = WebMessageBodyStyle.Bare)] //ResponseFormat = WebMessageFormat.Json
Stream GetJSON(); 

....
return new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
于 2013-04-10T08:48:58.727 回答