Web API: Client: Call a Web API from a .net client
原文地址: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
翻译地址:http://www.cnblogs.com/r01cn/archive/2012/11/20/2779011.html
Server Code:
1. 用EF创建Code First的Project;
2. 用VS创建Web API code;
Client Code:
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Test.EntityFramework.Models; namespace Test.WebAPI.Client { class Program { static void Main(string[] args) { // Unblock; TestUnblock(); Console.WriteLine("Unblock...");
// Unblock
Test();
// Block Test().Wait(); Console.WriteLine("Exist..."); Console.ReadLine(); } public static async Task Test() { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:55165/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync("api/test"); // Blocking call // Get if (response.IsSuccessStatusCode) { // Parse the response body. Blocking! var products = await response.Content.ReadAsAsync<IEnumerable<Test.EntityFramework.Models.Test>>(); foreach (var p in products) { Console.WriteLine("{0}\t{1};", p.ID, p.Title); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } // Post var testEntity = new Test.EntityFramework.Models.Test() { Number = 3, Title = "title3" }; response = await client.PostAsJsonAsync("api/test", testEntity); if (response.IsSuccessStatusCode) { Uri testEntityUrl = response.Headers.Location; // Put response = await client.GetAsync(testEntityUrl); testEntity = await response.Content.ReadAsAsync<Test.EntityFramework.Models.Test>(); testEntity.Title = "title3..."; response = await client.PutAsJsonAsync(testEntityUrl, testEntity); // Delete response = await client.DeleteAsync(testEntityUrl); } } } public static async void TestUnblock() { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:55165/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync("api/test"); // Blocking call // Get if (response.IsSuccessStatusCode) { // Parse the response body. Blocking! var products = await response.Content.ReadAsAsync<IEnumerable<Test.EntityFramework.Models.Test>>(); foreach (var p in products) { Console.WriteLine("{0}\t{1};", p.ID, p.Title); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } } } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步