开发者

How to consume REST service using http POST

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 = We开发者_Go百科bMessageFormat.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!


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜