Tôi cố gắng để đi qua một tutorial explaining how to access a WebAPI service trong VS2013 (.net 4.5.1) và tôi nhận được lỗi biên dịch với dòng:Làm cách nào để sử dụng HttpContentExtensions.ReadAsAsync <T>()?
Product product = await response.Content.ReadAsAsync<Product>();
response = await client.PostAsJsonAsync("api/products", gizmo);
và
response = await client.PutAsJsonAsync(gizmoUrl, gizmo);
Tôi đã tham chiếu System.Net. Http mà apparently chứa ba phương thức không biên dịch: ReadAsAsync(), PostAsJsonAsync() và PutAsJsonAsync(). Mặc dù các lớp mở rộng không xuất hiện trong ObjectBrowser cho hội đồng vì vậy tôi không thuyết phục tôi có phiên bản đúng (phiên bản tôi có là 4.0.30319.18402).
Tôi đang sử dụng gói Microsoft.AspNet.WebApi.Client mới nhất (5.1.2) để tôi nghĩ mình có mọi thứ cần thiết.
bất cứ ai có thể thấy tại sao mã không biên dịch hoặc những gì tôi đang mất tích:
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);
}
}
}
}
}
Cảm ơn.
bản sao có thể có của [Where is HttpContent.ReadAsAsync?] (Http://stackoverflow.com/questions/10399324/where-is-httpcontent-readasasync) –