如何使用HttpContentExtensions.ReadAsAsync<;T>;()

本文关键字:gt lt 何使用 HttpContentExtensions ReadAsAsync | 更新日期: 2023-09-27 18:00:48

我正在学习一个教程,解释如何在VS2013(.net 4.5.1)中访问WebAPI服务,但我遇到了以下几行的编译错误:

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(。虽然扩展类没有出现在程序集的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);
            }
        }
    }
}
}

谢谢。

如何使用HttpContentExtensions.ReadAsAsync<;T>;()

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

我觉得这是nuGet Microsoft.AspNet.WebApi.Client包的一部分。