我正在尝试通过一个解释如何访问WebAPI服务的教程在VS2013(.net 4.5.1)中进行学习,但是我遇到了以下代码出现编译错误:
Product product = await response.Content.ReadAsAsync<Product>();
response = await client.PostAsJsonAsync("api/products", gizmo);
并且
response = await client.PutAsJsonAsync(gizmoUrl, gizmo);
我已经引用了System.Net.Http,其中显然包含三个方法,但这些方法无法编译:ReadAsAsync()、PostAsJsonAsync()和PutAsJsonAsync()。尽管扩展类在程序集中未显示,因此我不能确定我是否拥有正确的版本(我拥有的版本是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);
}
}
}
}
}
谢谢。