将JSON对象发送到WCF Rest Service

时间:2013-04-09 05:22:44

标签: jquery asp.net wcf rest

我试图通过使用REST,WCF和JSON(所有这些技术的新手)来使我的应用程序正常工作。我让'GET'正常工作。正是“POST”导致了我的问题。

正如您将在下面看到的,我使用JSON.stringify打包'我的JSON,然后将POST发送到REST资源。但是,当对象到达处理请求的WCF方法时,对象始终为null。

以下是代码:

   $(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);
}
}

非常感谢

1 个答案:

答案 0 :(得分:0)

尝试:

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

....
return new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
相关问题