码迷,mamicode.com
首页 > Windows程序 > 详细

asp.net web api客户端调用

时间:2017-11-18 13:38:43      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:strong   head   code   bapi   post   fun   for   mod   mil   

服务接口

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

 

asp.net web api客户端调用

标签:strong   head   code   bapi   post   fun   for   mod   mil   

原文地址:http://www.cnblogs.com/hdwgxz/p/7856386.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!