简体   繁体   中英

Sending JSON object to WCF Rest Service

I am trying to get my application working by using REST, WCF and JSON (new to all those technologies). I have the 'GET' working fine. It is the 'POST' that is causing me problems.

As you will see below I 'pack up' my JSON using JSON.stringify, then fire off the POST to the REST resource. However, when the object gets to the WCF method that is handling the request the object is always null.

Here is the code:

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

   });

And the server side codes:

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

Many thanks

Try:

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

....
return new MemoryStream(Encoding.UTF8.GetBytes(jsonString));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM