WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递
上一讲中介绍了使用HttpClient如何去调用一个标准的Web Api接口,并且我们知道了Post,Put方法只能有一个FromBody参数,再有多个参数时,上讲提到,需要将它封装成一个对象进行传递,而这讲主要围绕这个话题来说,接口层添加一个新类User_Info,用来进行数据传递,而客户端使用网页ajax和控制台HttpClient的方式分别进行实现,Follow me!
下面定义一个复杂类型对象
- public class User_Info
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public string Info { get; set; }
- }
下面修改上次的api部分,让它对这个对象进行操作
- [CorsAttribute("http://localhost:3321")]
- public class RegisterController : ApiController
- {
- public static List<User_Info> Model = new List<User_Info>()
- {
- new User_Info{Id=,Name="zzl",Info="zzl是楼主"},
- new User_Info{Id=,Name="zhz",Info="zhz是zzl的儿子"},
- new User_Info{Id=,Name="zql",Info="zql是zzl的妻子"},
- new User_Info{Id=,Name="bobo",Info="bobo是zzl的朋友"}
- };
- // GET api/values
- public IEnumerable<User_Info> Get()
- {
- return Model;
- }
- // GET api/values/5
- public User_Info Get(int id)
- {
- var entity = Model.FirstOrDefault(i => i.Id == id);
- return entity;
- }
- // GET api/values/5?leval=1
- public HttpResponseMessage Get(int id, int leval)
- {
- return new HttpResponseMessage(HttpStatusCode.OK)
- {
- Content = new StringContent("<em style='color:red'>成功响应(id,level)</em>", System.Text.Encoding.UTF8, "text/html")
- };
- }
- // POST api/values
- public HttpResponseMessage Post([FromBody]User_Info value)
- {
- Model.Add(new User_Info
- {
- Id = value.Id,
- Info = value.Info,
- Name = value.Name,
- });
- //用户登陆相关
- return new HttpResponseMessage(HttpStatusCode.OK)
- {
- Content = new StringContent("添加数据成功,用户ID:" + value.Id, System.Text.Encoding.UTF8, "text/plain")
- };
- }
- // PUT api/values?userid=5
- public HttpResponseMessage Put(int userid, [FromBody]User_Info value)
- {
- var entity = Model.FirstOrDefault(i => i.Id == userid);
- entity.Info = value.Info;
- entity.Name = value.Name;
- return new HttpResponseMessage(HttpStatusCode.OK)
- {
- Content = new StringContent("修改数据成功,主键:" + userid + ",对象:" + value.Name)
- };
- }
- // DELETE api/values/5
- public HttpResponseMessage Delete(int id)
- {
- Model.Remove(Model.FirstOrDefault(i => i.Id == id));
- return new HttpResponseMessage(HttpStatusCode.OK)
- {
- Content = new StringContent("删除数据成功")
- };
- }
而最关键的地方还是在各个客户端调用的时候,首先,你不能指望客户端去引用你的程序集,因为,不能平台无法实现这种引用(java & c#,js & C#,php & c#),所以,在调用时需要有它们各自的方法,而JS的ajax调用时,直接使用json对象即可,键名对象
实体的属性,在使用HttpClient时,直接为FormUrlEncodedContent对象赋一个键值对的集合即可,下面分别介绍一下
HTML的JS实现
- $.ajax({
- url: "http://localhost:52824/api/register",
- type: "POST",
- data: { Id: 5, Name: '新来的', Info: '大家好' },//这里键名称必须为空,多个参数请传对象,api端参数名必须为value
- success: function (data) {
- console.log("post:" + data);
- }
- });
- $.ajax({
- url: "http://localhost:52824/api/register",
- type: "GET",
- success: function (data) {
- for (var i in data) {
- console.log(data[i].Id + " " + data[i].Name);
- }
- }
- });
结果截图
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAiUAAACWCAIAAACOzm9OAAAPXUlEQVR4nO3dT4/kRh3G8XpPffNr6XO9hojk0C+hNKeQHH0iEQiJ2Qpa2ABamijLEhGRUYhMgtBqQhayBCYKm7CKikO57HJV+U/PtMvu3u9Hq9WM2y67q2f8uGyPf+IaAID5iaU3AADwUlhT3pRbIYTYlvO0vNntU1OOstKmkfneQk5xdy3VCIAzcqy82e82wrct3V7Y2ex2ne/d1H3TRnpnHUy9zR693IaLtFNWlDd9C5dBv3nbHfZi52OoW0rP2Wm6u864u0bZ9UYf5p26NW4z3MYjBvvV5cWudnF5Zddf1hNKtwXxlGQDroWrywvXll00XCyxUuCcpfPm7QePX3vznVdev+f/e+3Nd3787h9Ssyf3Wr37hN79yFx5s99tgiW8KSeTN8H0cltP8LrTm9F+WU+N5/QbDtuOu+sWjtLIgGPnzb50YbAvdxeX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mSIHOepDj5Yr7shtDQuqmydFGfbYZyoQCwPGtoJ70hFoBtpRapWVdvlPK5rnPWmu3cB0+dfGbepSi1YFjHspSA8AMVlBPevL+vdK6sqGiq2RB0MG88UZARd+Uw7YHADDJSupJV6qQUk449VUppYNSnlp2oqLOGK1Ulcgbe2uBXwQ0mmJS3wMAjmD5etJGS688Wv8F/0opKYXUVVUZo5XSVWUqrav28n5zLSeZN8GqeqeQNwAwhxXUk55S9blSRT34sWmgldKqKOx/za0DNmFs7MR506xnYIox5A0AzGIV9aSnVH22UeRSRCtVef/Vk7SSqqpHOe39abZR7361ekQTT/Ev6fCHPABwXCdTT9oFi42JnpNg7V98NqOU9B+KAgDWjefZAAByIG8AADmQNwCAHMgbAEAO1JMGAOTA+AYAkAN5AwDIgbwBAOTwf6NZ86DAqT09AAAAAElFTkSuQmCC" alt="" />
Console程序中使用HttpClient对象进行实现
- /// <summary>
- /// HttpClient实现Post请求
- /// </summary>
- static async void dooPost()
- {
- string url = "http://localhost:52824/api/register";
- //设置HttpClientHandler的AutomaticDecompression
- var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
- //创建HttpClient(注意传入HttpClientHandler)
- using (var http = new HttpClient(handler))
- {
- //使用FormUrlEncodedContent做HttpContent
- var content = new FormUrlEncodedContent(new Dictionary<string, string>()
- { {"Id","6"},
- {"Name","添加zzl"},
- {"Info", "添加动作"}//键名必须为空
- });
- //await异步等待回应
- var response = await http.PostAsync(url, content);
- //确保HTTP成功状态值
- response.EnsureSuccessStatusCode();
- //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
- Console.WriteLine(await response.Content.ReadAsStringAsync());
- }
- }
- /// <summary>
- /// HttpClient实现Get请求
- /// </summary>
- static async void dooGet()
- {
- string url = "http://localhost:52824/api/register?id=1";
- //创建HttpClient(注意传入HttpClientHandler)
- var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
- using (var http = new HttpClient(handler))
- {
- //await异步等待回应
- var response = await http.GetAsync(url);
- //确保HTTP成功状态值
- response.EnsureSuccessStatusCode();
- //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
- Console.WriteLine(await response.Content.ReadAsStringAsync());
- }
- }
- /// <summary>
- /// HttpClient实现Put请求
- /// </summary>
- static async void dooPut()
- {
- var userId = 1;
- string url = "http://localhost:52824/api/register?userid=" + userId;
- //设置HttpClientHandler的AutomaticDecompression
- var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
- //创建HttpClient(注意传入HttpClientHandler)
- using (var http = new HttpClient(handler))
- {
- //使用FormUrlEncodedContent做HttpContent
- var content = new FormUrlEncodedContent(new Dictionary<string, string>()
- {
- {"Name","修改zzl"},
- {"Info", "Put修改动作"}//键名必须为空
- });
- //await异步等待回应
- var response = await http.PutAsync(url, content);
- //确保HTTP成功状态值
- response.EnsureSuccessStatusCode();
- //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
- Console.WriteLine(await response.Content.ReadAsStringAsync());
- }
- }
WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递的更多相关文章
- WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递 【转】
原文:http://www.cnblogs.com/lori/p/4045633.html 下面定义一个复杂类型对象 public class User_Info { public int Id { ...
- 通过HttpClient来调用Web Api接口~续~实体参数的传递
并且我们知道了Post,Put方法只能有一个FromBody参数,再有多个参数时,上讲提到,需要将它封装成一个对象进行传递,而这讲主要围绕这个话题来说,接口层添加一个新类User_Info,用来进行数 ...
- 通过HttpClient来调用Web Api接口,实体参数的传递
下面定义一个复杂类型对象 public class User_Info { public int Id { get; set; } public string Name { get; set; } p ...
- Http下的各种操作类.WebApi系列~通过HttpClient来调用Web Api接口
1.WebApi系列~通过HttpClient来调用Web Api接口 http://www.cnblogs.com/lori/p/4045413.html HttpClient使用详解(java版本 ...
- WebApi系列~通过HttpClient来调用Web Api接口
回到目录 HttpClient是一个被封装好的类,主要用于Http的通讯,它在.net,java,oc中都有被实现,当然,我只会.net,所以,只讲.net中的HttpClient去调用Web Api ...
- 通过HttpClient来调用Web Api接口
回到目录 HttpClient是一个被封装好的类,主要用于Http的通讯,它在.net,java,oc中都有被实现,当然,我只会.net,所以,只讲.net中的HttpClient去调用Web Api ...
- c# 【MVC】WebApi通过HttpClient来调用Web Api接口
/// <summary> /// HttpClient实现Post请求(异步) /// </summary> static async void dooPost() { st ...
- WebApi~通过HttpClient来调用Web Api接口
异步请求 ///<summary> /// HttpClient实现Post请求(异步) /// </summary> static async void dooPost() ...
- 【WebApi】通过HttpClient调用Web Api接口
HttpClient是一个封装好的类,它在很多语言中都有被实现,现在HttpClient最新的版本是4.5. 它支持所有的http方法,自动转向,https协议,代理服务器. 一.Api接口参数标准化 ...
随机推荐
- 慕课网Java高并发秒杀学习
课程地址:http://www.imooc.com/learn/587 一个很好:spring,springMVC,mybatis,bootstrap,jQuery,mysql,Restful学习案例 ...
- Map中的entry
是java中的一个对象,一般可以通过map.entrySet()得到.1,entrySet实现了Set接口,里面存放的是键值对.一个K对应一个V.2,用来遍历map的一种方法.Set<Map.E ...
- Java变量自增和自减运算符的用法
1.后加加(num++): 先输出运算结果再加加: public static void main(String[] args){ int num=10; int p1=num++; System. ...
- linux环境下安装mongodb
最近有用到mongodb,顺便找到了以前的指南,顺便写一篇随笔,以后或许有用到的地方. 第一步:下载mongodb的linux版本,mongodb-linux-x86_64-3.2.4.tgz(去官网 ...
- 8天入门wpf(转)
8天入门wpf—— 第一天 基础概念介绍 8天入门wpf—— 第二天 xaml详解 8天入门wpf—— 第三天 样式 8天入门wpf—— 第四天 模板 8天入门wpf—— 第五天 数据绑定 8天入门w ...
- 轻量级ORM框架 Dapper快速学习
好在有师兄师姐一起带着做,所以开始没那么困难,但是由于大学涉猎范围有限,往往有很尴尬的时候,不懂构造方法重载,去“请教”,本来以为师兄会帮忙写好,结果“我念,你来写”,被深深的激励了一把,后来就早出晚 ...
- linux进程间通信-共享内存
转载:http://www.cnblogs.com/fangshenghui/p/4039720.html 一 共享内存介绍 共享内存可以从字面上去理解,就把一片逻辑内存共享出来,让不同的进程去访问它 ...
- 51NOD算法马拉松11 B君的竞技场
传送门 这题我在比赛的时候竟然没有想出来,真是-- 这道题我们可以想一想怎么搞定获胜的概率p. 我们发现再怎么这个p都是搞不了的.所以我们可以积一下分,然后就可以不用去管p了.我们要做的就是求出一个关 ...
- jetty9 安装部署更改端口号
1.下载jetty 并解压到指定目录 2.更改默认端口号--在start.d中的http.ini中修改 3.启动服务 在jetty的根目录中输入命令 java -jar start.jar 服务就启 ...
- Software Project Management hw1
I just want to say something about my java project that I did last year. Our task is to finish a lin ...