Search code examples
c#.netwcfjsonwcf-rest

RESTful WCF json request and json response returns null


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

}


Solution

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