Generic HttpClient.GetAsync

Recently I needed to make calls to several WebApi controllers from C# code and, instead of having code duplication throughout my application, I wrote a little generic class that wrapped the call logic.

I ended up with the following class:

public class AsyncHttpClient<T> where T : new()
{
    public async Task<T> GetAsync(Uri baseAddress, string uri)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = baseAddress;
            client.DefaultRequestHeaders.Accept.Clear();

            HttpResponseMessage response = await client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsAsync<T>();
            }
        }

        return new T();
    }
}

Making the calls is as easy as:

SomeObject someObject = new AsyncHttpClient<SomeObject>()
                        .GetAsync(new Uri("http://my.api.com/"),
                                  "api/MyController?SomeParam=123").Result;
comments powered by Disqus