Skip to content

Making a GET Request in C# using HttpClient

With my new job at New Orbit I am moving towards full stack web development in ASP.NET and AngularJS. The first issue I encountered was how to make a GET request to an external API.

WebClient vs HttpWebRequest vs HttpClient. Which one?!

It doesn’t help that are multiple options. Such as the WebClient, HttpWebRequest and HttpClient classes which all can be used to make a GET request – so which one to choose? Diogo Nunes has a nice discussion of the differences. After speaking with one of the Principle developers here it seemed HttpClient was the best option. Compared to WebClient it is closer to the HTTP specification and is less verbose than HttpWebRequest. Although it does need .NET 4.5 which may be an issue on older projects.

An Example

Below is an example of how to use HttpClient to make a GET request to your target API. In this instance I was looking to get my user profile information from GitHub for as part of a wider experiment with AngularJS. Although in practise you might be better off using the Octokit library for interactions with the GitHub API.

Most of the code is straightforward enough. The only subtlety is adding a User-Agent header which is required by the GitHub API. It is added at line 21 which creates the User-Agent in the JSON header of the request.

Published inC#WebAPI

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *