[聚合文章] asp.net web api客户端调用

.Net 2017-11-18 1 阅读

服务接口

接口 1:

//Post:http://127.0.0.1/HY_WebApi/api/V2/Key/FunctionTest1
[HttpPost]
public HttpResponseMessage FunctionTest1(Model1 model)
{
  ......          
}

接口 2:

//Post:http://127.0.0.1/HY_WebApi/api/V2/Key/FunctionTest2
[HttpPost]
public HttpResponseMessage FunctionTest2(Model2 model)
{
  ......          
}

接口参数:

public class Model1
{
public List<Model2> List1 { get; set; }
public string Name { get; set; }
}

public class Model2
{
public string Field21{get;set;}
public string Field22{get;set;}
}

客户端调用

对于接口 1:采用StringContent,将所传数据序列化后写入请求消息体中。

var m1 = new { List1 = new List<object> { new { Field21 = "Field21", Field22 = "Field21" }, new { Field21 = "Field21", Field22 = "Field21" } }, Name = "Tests" };
HttpContent content = new StringContent(JsonConvert.SerializeObject(m1));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
HttpClient client = new HttpClient();
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, @"http://192.168.20.104/HY_WebApi/api/V2/Key/FunctionTest1"))
{
  request.Content = content;
  HttpResponseMessage response = client.SendAsync(request).Result;
  var r = response.Content.ReadAsAsync<object>();
  r.Wait();
  var s = r.Result.ToString();
}

如若采用 FormUrlEncodedContent 则无法成功。

调用接口 2传参的方式有两种

第一种方法:采用 FormUrlEncodedContent将请求输入写入消息体中

HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>()       
{   
  {"Field21","Field21"},
  {"Field22","Field22"}
});
HttpClient client = new HttpClient();
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, @"http://192.168.20.104/HY_WebApi/api/V2/Key/FunctionTest2"))
{
  request.Content = content;
  HttpResponseMessage response = client.SendAsync(request).Result;
  var r = response.Content.ReadAsAsync<object>();
  r.Wait();
}

第二种方法: 采用 StringContent 将请求数据写入消息体中

var model = new { Field21 = "Field21", Field22 = "Field22" };
HttpContent content = new StringContent(JsonConvert.SerializeObject(model));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, @"http://192.168.20.104/HY_WebApi/api/V2/Key/FunctionTest2"))
{
  request.Content = content;
  HttpResponseMessage response = client.SendAsync(request).Result;
  var r = response.Content.ReadAsAsync<object>();
  r.Wait();
}

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。