webapi怎么调用?如何使用程序调用webApi接口?
在C#中,传统调用HTTP接口一般有两种办法:
1.WebRequest/WebResponse组合的方法调用
2.WebClient类进行调用。
第一种方法抽象程度较低,使用较为繁琐;而WebClient主要面向了WEB网页场景,在模拟Web操作时使用较为方便,但用在RestFul场景下却比较麻烦,在Web API发布的同时,.NET提供了两个程序集:System.Net.Http和System.Net.Http.Formatting。这两个程序集中最核心的类是HttpClient。
在.NET4.5中带有这两个程序集,而.NET4需要到Nuget里下载Microsoft.Net.Http和Microsoft.AspNet.WebApi.Client这两个包才能使用这个类,更低的.NET版本就只能表示遗憾了只能用WebRequest/WebResponse或者WebClient来调用这些API了。
在使用中,System.Net.Http这个程序集提供了HttpClient类以及相关的HTTP调用,而System.Net.Http.Formatting提供了一些针对HttpClient的帮助扩展,更好地支持了内容协商、Content创建等功能。
下面我就和大家一起写一下这个例子:
public class Person { public long Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Sex { get; set; } public override string ToString() { return $"Id={Id} Name={Name} Age={Age} Sex={Sex}"; } }class Program { static void Main(string[] args) { var client = new HttpClient(); //基本的API URL client.BaseAddress = new Uri("http://localhost:22658/"); //默认希望响应使用Json序列化(内容协商机制,我接受json格式的数据) client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //运行client接收程序 Run(client); Console.ReadLine(); } //client接收处理(都是异步的处理) static async void Run(HttpClient client) { //post 请求插入数据 var result = await AddPerson(client); Console.WriteLine($"添加结果:{result}"); //添加结果:true //get 获取数据 var person = await GetPerson(client); //查询结果:Id=1 Name=test Age=10 Sex=F Console.WriteLine($"查询结果:{person}"); //put 更新数据 result = await PutPerson(client); //更新结果:true Console.WriteLine($"更新结果:{result}"); //delete 删除数据 result = await DeletePerson(client); //删除结果:true Console.WriteLine($"删除结果:{result}"); } //post static async Task AddPerson(HttpClient client) { //向Person发送POST请求,Body使用Json进行序列化 return await client.PostAsJsonAsync("api/Person