关于web api 2 客户端请求Post

(一)、客户端的部分代码[需要添加NuGet程序包]

附:Client 声明方法

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8800/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

1. 准备一个post对象

var requestJson = JsonConvert.SerializeObject(new { Id = 1, Name = "test", Category = "1", Price = 1 });

2. 序列化成接json字符串

string requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(pd);

3. 创建HttpContent 对象,包装json字符串

HttpContent httpContent = new StringContent(requestJson);

4. 设置接收数据方式
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

5. 发送Post请求

response = client.PostAsync("http://localhost:9014/api/products/PostProduct", httpContent).Result;

6.接收返回参数

(二)、服务端

用对象接收,这里传过来的json字符串会自动转化为对象

public string PostProduct([FromBody]Product pd)
{
  lis.Add(pd);

  //返回json字符串
  return DataHelper.ObjToJson(pd);

}

原文地址:https://www.cnblogs.com/yougmi/p/3996517.html