如何使用http POST使用REST服务

时间:2010-10-16 00:47:50

标签: http rest post

我定义了REST服务的WCF实现:

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

Get操作很简单。如果客户端没有代理生成,我不知道如何使用POST服务。任何代码示例将不胜感激!

1 个答案:

答案 0 :(得分:0)

如果您在客户端也有客户对象,则可以使用Microsoft.Http库并执行:

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

如果您想避免使用客户对象,您可以将JSON构建为字符串,然后创建如下内容:

var content = HttpContent.Create("{...Json...}", "application/json");