asp.net web api客户端调用

时间:2022-05-03
本文章向大家介绍asp.net web api客户端调用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

服务接口

接口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();
}