tags:

views:

29

answers:

1

I defined a WCF implementation of REST service:

enter code here
[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(UriTemplate = "customers/{id}", ResponseFormat = WebMessageFormat.Json)]
    Customer GetCustomer(string id);

    [OperationContract]
    [WebInvoke(UriTemplate = "customers", ResponseFormat = WebMessageFormat.Json)]
    Customer PostCustomer(Customer c);
}


public class Service : IService
{
    public Customer GetCustomer(string id)
    {
        return new Customer { ID = id, Name = "Demo User" };
    }

    public Customer PostCustomer(Customer c)
    {
        return new Customer { ID = c.ID, Name = "Hello, " + c.Name };
    }
}


[DataContract(Namespace = "")]
public class Customer
{
    [DataMember]
    public string ID { get; set; }
    [DataMember]
    public string Name { get; set; }
}

The Get operation is easy. Without proxy generation on the client side, I am not sure how to consume the POST service. Any code sample will be appreciated!

A: 

If you have the customer object on the client side also, you can use the Microsoft.Http libraries and do:

var client = new HttpClient()
var customer = new Customer() {ID=2, Name="Foo"};
var content = HttpContent.CreateJsonDataContract<Customer>(customer);
client.Post(new Uri("http://example.org/customers"),content);

if you want to avoid using a customer object, you can just build the JSON as a string and then create the content like this:

var content = HttpContent.Create("{...Json...}", "application/json");
Darrel Miller
I installed WCF REST StarterKit Preview 2 and added Microsoft.Http reference. But the HttpContent doesn't have CreateJsonDatContract?
Icerman
@Icerman It's in the Microsoft.Http.Extensions DLL
Darrel Miller
After changed to HttpContentExtensions.CreateJsonDataContract(), it worked. Thanks!
Icerman