通过HttpClient来调用Web Api接口,实体参数的传递

时间:2021-12-20 05:06:56

下面定义一个复杂类型对象

public class User_Info { public int Id { get; set; } public string Name { get; set; } public string Info { get; set; } }

下面修改上次的api部分,让它对这个对象进行操作

[CorsAttribute(":3321")] public class RegisterController : ApiController { public static List<User_Info> Model = new List<User_Info>() { new User_Info{Id=1,Name="zzl",Info="zzl是楼主"}, new User_Info{Id=2,Name="zhz",Info="zhz是zzl的儿子"}, new User_Info{Id=3,Name="zql",Info="zql是zzl的妻子"}, new User_Info{Id=4,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实现