I\'m playing a little bit with this new technology in .net 4.5, I would like to check the code for this call and how should I control the errors or the response of my async
Is this the better way to do it?
The response.EnsureSuccessStatusCode();
will throw an exception if the status code returned by your remote service is different than 2xx. So you might want to use the IsSuccessStatusCode
property instead if you want to handle the error yourself:
public async Task<ActionResult> Index()
{
using (HttpClient client = new HttpClient())
{
var response = await client.GetAsync("http://mywebapiservice");
string content = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var model = JsonConvert.DeserializeObject<Tweets>(content);
return View(model.results);
}
// an error occurred => here you could log the content returned by the remote server
return Content("An error occurred: " + content);
}
}