原文地址: 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); } } } } }
Web API: Client: Call a Web API from a .net client,布布扣,bubuko.com