Asynchronous calls using HttpClient on MVC4

I will play a little with this new technology in .net 4.5, I would like to check the code for this call and how can I manage the errors or the response of my asynchronous call. The call works fine, I need full control over the possible errors returned from my service.

this is my code:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace TwitterClientMVC.Controllers { public class Tweets { public Tweet[] results; } public class Tweet { [JsonProperty("from_user")] public string UserName { get; set; } [JsonProperty("text")] public string TweetText { get; set; } } } public async Task<ActionResult> Index() { Tweets model = null; HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync("http://mywebapiservice"); response.EnsureSuccessStatusCode(); model = JsonConvert.DeserializeObject<Tweets>(response.Content.ReadAsStringAsync().Result); return View(model.results); } 

Is this the best way to do this? or am I missing something? Thanks

I will reorganize it, is it also an async method?

 public async Task<ActionResult> Index() { Tweets model = null; using (HttpClient httpclient = new HttpClient()) { model = JsonConvert.DeserializeObject<Tweets>( await httpclient.GetStringAsync("http://search.twitter.com/search.json?q=pluralsight") ); } return View(model.results); } 
+4
source share
1 answer

Is this the best way to do this?

response.EnsureSuccessStatusCode(); Throws an exception if the status code returned by your remote service is different from 2xx. Thus, 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); } } 
+5
source

All Articles