I'm making a client using Web Api. My site has the Web server function Api. I found this reference from Microsoft link which has an example client:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
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);
}...
The interesting thing is that the line below hangs and dies:
HttpResponseMessage response = await client.GetAsync("api/products/1");
Searching the internet, I implemented this code that works:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:17694/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = client.GetAsync("api/Integracao/GetAllProducts/").Result;
if (response.IsSuccessStatusCode)
{
var product = response.Content.ReadAsStringAsync();
var dados = JsonConvert.DeserializeObject<List<TipoPessoa>>(product.Result);
}
else
{
Console.WriteLine("Error");
}
}
}
My question is, what's the big difference between these two codes. Is my implementation acceptable?
Microsoft:
HttpResponseMessage response = await client.GetAsync("api/products/1");
My code:
HttpResponseMessage response = client.GetAsync("api/Integracao/GetAllProducts/").Result;