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

}

5
  • What does return new mytype mean? What is mytype? Commented Dec 24, 2010 at 0:36
  • edited for the correct code.. that was typo Commented Dec 24, 2010 at 1: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. Commented Dec 29, 2010 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 Commented Jan 3, 2011 at 15:34
  • See stackoverflow.com/questions/5685045/… Commented Feb 6, 2013 at 14:32

4 Answers 4

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)
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

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""}}.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.