我如何使用HttpContentExtensions.ReadAsAsync <t>()?</t>

时间:2014-04-29 10:55:36

标签: c# asp.net asp.net-web-api

我正在尝试通过VS2013中的tutorial explaining how to access a WebAPI service(.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,其中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);
            }
        }
    }
}
}

感谢。

1 个答案:

答案 0 :(得分:15)

原来我需要对System.Net.Http.Formatting的引用。

我得到的印象是这是nuGet Microsoft.AspNet.WebApi.Client软件包的一部分。