简体   繁体   中英

How can I use HttpContentExtensions.ReadAsAsync<T>()?

I am trying to go through a tutorial explaining how to access a WebAPI service in VS2013 (.net 4.5.1) and I get compilation errors with lines :

Product product = await response.Content.ReadAsAsync<Product>();
response = await client.PostAsJsonAsync("api/products", gizmo);

and

response = await client.PutAsJsonAsync(gizmoUrl, gizmo);

I've referenced System.Net.Http which apparently contains the three methods which fails to compile: ReadAsAsync(), PostAsJsonAsync() and PutAsJsonAsync(). Although the extensions class does not appear in the ObjectBrowser for the assembly so I'm not convinced I have the right version (version I have is 4.0.30319.18402).

I'm using the latest nuGet Microsoft.AspNet.WebApi.Client package (5.1.2) so I think I have everything required.

Can anyone see why the code doesn't compile or what I'm missing:

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);
            }
        }
    }
}
}

Thanks.

Turns out I needed a reference to System.Net.Http.Formatting.

I'd got the impression this was part of the nuGet Microsoft.AspNet.WebApi.Client package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM