前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >asp.net web api客户端调用

asp.net web api客户端调用

作者头像
甜橙很酸
发布2018-03-08 11:09:29
3.4K0
发布2018-03-08 11:09:29
举报
文章被收录于专栏:DOTNETDOTNET

服务接口

接口1:

代码语言:javascript
复制
//Post:http://127.0.0.1/HY_WebApi/api/V2/Key/FunctionTest1
[HttpPost]
public HttpResponseMessage FunctionTest1(Model1 model)
{
  ......          
}

接口2:

代码语言:javascript
复制
//Post:http://127.0.0.1/HY_WebApi/api/V2/Key/FunctionTest2
[HttpPost]
public HttpResponseMessage FunctionTest2(Model2 model)
{
  ......          
}

接口参数:

代码语言:javascript
复制
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,将所传数据序列化后写入请求消息体中。

代码语言:javascript
复制
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将请求输入写入消息体中

代码语言:javascript
复制
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将请求数据写入消息体中

代码语言:javascript
复制
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();
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-11-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档