我試圖在VS2013(.NET 4.5.1)要經過tutorial explaining how to access a WebAPI service和我與行編譯錯誤:我如何使用HttpContentExtensions.ReadAsAsync <T>()?
Product product = await response.Content.ReadAsAsync<Product>();
response = await client.PostAsJsonAsync("api/products", gizmo);
和
response = await client.PutAsJsonAsync(gizmoUrl, gizmo);
我引用System.Net。其中apparently包含三個無法編譯的方法:ReadAsAsync(),PostAsJsonAsync()和PutAsJsonAsync()。儘管擴展類沒有出現在組件的ObjectBrowser中,所以我不確定我的版本是否正確(版本是4.0.30319.18402)。
我使用的是最新的NuGet Microsoft.AspNet.WebApi.Client包(5.1.2),所以我認爲我擁有所需的一切。
有人能看到爲什麼代碼不會編譯或我錯過了什麼:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace WebApiClient
{
class Program
{
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:54122/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
//***********
Product product = await response.Content.ReadAsAsync<Product>();
//***********
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
//***********
response = await client.PostAsJsonAsync("api/products", gizmo);
//***********
if (response.IsSuccessStatusCode)
{
Uri gizmoUrl = response.Headers.Location;
// HTTP PUT
gizmo.Price = 80; // Update price
//***********
response = await client.PutAsJsonAsync(gizmoUrl, gizmo);
//***********
// HTTP DELETE
response = await client.DeleteAsync(gizmoUrl);
}
}
}
}
}
感謝。
可能重複[Where is HttpContent.ReadAsAsync?](http://stackoverflow.com/questions/10399324/where-is-httpcontent-readasasync) –