.NET Tips and Tricks

Blog archive

Pulling Objects from Web Services with ReadAsAsync

In an earlier post, I discussed the three objects that Microsoft has provided for calling Web Services: HttpWebRequest, WebClient and HttpClient. At the time, I suggested WebClient was the simplest solution, unless you wanted to take advantage of HttpClient's asynchronous processing.

I've reconsidered that choice since then and I'm currently using HttpClient almost exclusively. Part of the reason is that HttpClient gives me the ReadAsAsync method. To understand why I like that method so much, you have to compare it to the alternatives.

Here's how to get a list of Customer objects out of the response from a Web Service using the traditional ReadAsStringAsync method:

HttpClient hc = new HttpClient();
HttpResponseMessage customersRm = await hc.GetAsync(url);
string customersString = await customersRm.Content.ReadAsStringAsync();
List<Customer> custs = JsonConvert.DeserializeObject<List<Customer>>(customersString);

Now here's the code using ReadAsAsync (even the method name is shorter!):

HttpClient hc = new HttpClient();
HttpResponseMessage customersRm = await hc.GetAsync(url);
List<Customer> custs = await customersRm.Content.ReadAsAsync<List<Customer>>();

The only problem is that you don't, in .NET 4.5 or later, get ReadAsAsync without some work -- you'll have to add the Microsoft.AspNet.WebApi.Client NuGet package to your project to pick up this extension method. I think that's worth doing.

Posted by Peter Vogel on 04/25/2019


comments powered by Disqus

Featured

Subscribe on YouTube