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.
ReadAsAsync Method (HttpContent, Type, CancellationToken) Returns a Task that will yield an object of the specified type from the content instance using one of the provided formatters to deserialize the content.
A base class representing an HTTP entity body and content headers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With