4
I am making a client using Web Api. My site has the server function of the Web Api. I found this reference from Microsoft http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client that has a client example:
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 in 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 is the big difference between these two codes. My implementation is acceptable?
Microsoft:
HttpResponseMessage response = await client.GetAsync("api/products/1");
My code:
HttpResponseMessage response = client.GetAsync("api/Integracao/GetAllProducts/").Result;
I found out why await does not work in my case. In the microsoft link is the event call:
RunAsync().Wait();
. If I doRunAsync();
works. Is there something missing. Another detail ofRunAsync();
, Because this call is not awaited, Execution of the Current method continues before the call is completed. Consider Applying the 'await' Operator to the result of the call. E: webapi converter Form1.Cs 43 13 converter– Tiedt Tech
You can do the method that called the
RunAsync()
be asynchronous as well (using the modifierasync
), and with that you can callawait RunAsync()
.– carlosfigueira