2

I am trying to build a sample for RESTful WCF. The request and response is JSON. The response that I get is:

{"FirstName":null,"LastName":null}

I need to get proper response.

Here is the code:

Web.config has configuration for Restful:

service contract:

[OperationContract]
        [WebInvoke(UriTemplate = "Data", 
            ResponseFormat = WebMessageFormat.Json)]
        person getData(person name);

Implementation:

public person getData(person name)
{
    return new person{ FirstName= name.FirstName, LastName= name.LastName };
}

[DataContract]

public class person 
{

[DataMember]
public string FirstName;

[DataMember]
public string LastName;
}

Client:

class Program
{
static void Main(string[] args)
{
            string baseAddress = "http://localhost/RESTfulService";
 SendRequest(baseAddress + "/Data", "POST", "application/json", @"{""getData"" : {""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}}");
}

  public static string SendRequest(string uri, string method, string contentType, string body)

    {
        string responseBody = null;

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
        req.Method = method;
        if (!String.IsNullOrEmpty(contentType))
        {
            req.ContentType = contentType;
        }
        if (body != null)
        {
            byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
            req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
            req.GetRequestStream().Close();
        }

        HttpWebResponse resp;
        try
        {
            resp = (HttpWebResponse)req.GetResponse();
        }
        catch (WebException e)
        {
            resp = (HttpWebResponse)e.Response;
        }
        Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
        foreach (string headerName in resp.Headers.AllKeys)
        {
            Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
        }
        Console.WriteLine();
        Stream respStream = resp.GetResponseStream();
        if (respStream != null)
        {
            responseBody = new StreamReader(respStream).ReadToEnd();
            Console.WriteLine(responseBody);
        }
        else
        {
            Console.WriteLine("HttpWebResponse.GetResponseStream returned null");
        }
        Console.WriteLine();
        Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ");
        Console.WriteLine();

        return responseBody;
    }

}

genericuser
  • 1,430
  • 4
  • 22
  • 40
  • What does `return new mytype` mean? What is `mytype`? – Aliostad Dec 24 '10 at 00:36
  • edited for the correct code.. that was typo – genericuser Dec 24 '10 at 01:07
  • Just as a side note: You're using wrapped messages, i.e. the method name (getData) is also part of the message. Is this really a RESTful service or just SOAP in JSON disguise? If find it far more elegant to use bare messages: ([WebInvoke(UriTemplate = "Data/getData", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]. This could also be part of your problem because I suspect that your message isn't quite what WCF expects. – Codo Dec 29 '10 at 18:00
  • you are correct, I need to use this service as SOAP and RESTful. can it be achieved, I tried it even with bare, it still doesnt work – genericuser Jan 03 '11 at 15:34
  • See http://stackoverflow.com/questions/5685045/how-to-not-return-null-when-a-data-member-field-is-not-set-in-the-data-contract – David d C e Freitas Feb 06 '13 at 14:32

4 Answers4

1
public static string SendRequest(string uri, string method, string contentType, string body) {...}

somehow it works only fine for "GET" methods.

For POST methods, I had to call the service operations in different manner on the client side:

uri = "http://localhost/RestfulService";

EndpointAddress address = new EndpointAddress(uri);
WebHttpBinding binding = new WebHttpBinding();
WebChannelFactory<IRestfulServices> factory = new WebChannelFactory<IRestfulServices>(binding, new Uri(uri));
IRestfulServices channel = factory.CreateChannel(address, new Uri(uri));

channel.getData(new Person{firstName = 'John', LastName = 'Doe'});

[ServiceContract]
public interface IRestfulService
{
    [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "Data")]
    object getData(Person name)
}
David d C e Freitas
  • 7,481
  • 4
  • 58
  • 67
genericuser
  • 1,430
  • 4
  • 22
  • 40
0

Problem:

Getting an empty JSON response of { }

enter image description here

The Interface:

[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "Client/{idsHashed}", ResponseFormat = WebMessageFormat.Json)]
Summary GetClientDataById(string idsHashed);

The web method:

public Summary GetClientDataById(string idsHashed)
{
    Summary clientSum = new Summary().GetClientDataById(clientId);
    return clientSum;
}

In the class, I had turned the fields to internal and private!!!

public class Summary
{
    private string clientName { get; set; }  //<--  wont be rendered out as json because its private

Solution:

Check class properties are Public.

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
0

1.Method name is not required for the restful wcf. 2.Json deserializer does not require parameter name, it treat it as property name. So use {""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}" instead of {""getData"" : {""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}}.

xdtTransform
  • 1,986
  • 14
  • 34
Sumit Murari
  • 1,597
  • 3
  • 28
  • 43
0

I believe the DataContract object needs to have a parameterless constructor for the serializer to work correctly. I.e. public Person() { }, also you may need to add getters and setters for your public members, public string FirstName{ get; set; }.

JMorgan
  • 805
  • 4
  • 11
  • 24