WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递 【转】

时间:2021-11-28 13:01:53

原文:http://www.cnblogs.com/lori/p/4045633.html

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

WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递 【转】
   public class User_Info
{
public int Id { get; set; }
public string Name { get; set; }
public string Info { get; set; }
}
WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递 【转】

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

WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递 【转】
    [CorsAttribute("http://localhost: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("删除数据成功")
};
}
WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递 【转】

而最关键的地方还是在各个客户端调用的时候,首先,你不能指望客户端去引用你的程序集,因为,不能平台无法实现这种引用(java & c#,js & C#,php & c#),所以,在调用时需要有它们各自的方法,而JS的ajax调用时,直接使用json对象即可,键名对象

实体的属性,在使用HttpClient时,直接为FormUrlEncodedContent对象赋一个键值对的集合即可,下面分别介绍一下

HTML的JS实现

WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递 【转】
     $.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);
}
}
});
WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递 【转】

结果截图

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAiUAAACWCAIAAACOzm9OAAAPXUlEQVR4nO3dT4/kRh3G8XpPffNr6XO9hojk0C+hNKeQHH0iEQiJ2Qpa2ABamijLEhGRUYhMgtBqQhayBCYKm7CKikO57HJV+U/PtMvu3u9Hq9WM2y67q2f8uGyPf+IaAID5iaU3AADwUlhT3pRbIYTYlvO0vNntU1OOstKmkfneQk5xdy3VCIAzcqy82e82wrct3V7Y2ex2ne/d1H3TRnpnHUy9zR693IaLtFNWlDd9C5dBv3nbHfZi52OoW0rP2Wm6u864u0bZ9UYf5p26NW4z3MYjBvvV5cWudnF5Zddf1hNKtwXxlGQDroWrywvXll00XCyxUuCcpfPm7QePX3vznVdev+f/e+3Nd3787h9Ssyf3Wr37hN79yFx5s99tgiW8KSeTN8H0cltP8LrTm9F+WU+N5/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/sPk5aSuUFTP2YzjuvibrWALC4efKmeazmSIHOepDj5Yr7shtDQuqmydFGfbYZyoQCwPGtoJ70hFoBtpRapWVdvlPK5rnPWmu3cB0+dfGbepSi1YFjHspSA8AMVlBPevL+vdK6sqGiq2RB0MG88UZARd+Uw7YHADDJSupJV6qQUk449VUppYNSnlp2oqLOGK1Ulcgbe2uBXwQ0mmJS3wMAjmD5etJGS688Wv8F/0opKYXUVVUZo5XSVWUqrav28n5zLSeZN8GqeqeQNwAwhxXUk55S9blSRT34sWmgldKqKOx/za0DNmFs7MR506xnYIox5A0AzGIV9aSnVH22UeRSRCtVef/Vk7SSqqpHOe39abZR7361ekQTT/Ev6fCHPABwXCdTT9oFi42JnpNg7V98NqOU9B+KAgDWjefZAAByIG8AADmQNwCAHMgbAEAO1JMGAOTA+AYAkAN5AwDIgbwBAOTwf6NZ86DAqT09AAAAAElFTkSuQmCC" alt="" />

Console程序中使用HttpClient对象进行实现

WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递 【转】
       /// <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接口~续~实体参数的传递 【转】