How to use HTTP Client in C#
Introduction
HttpClient is a class in C# that is used for making HTTP calls of different kinds (most commonly Get/Put/Delete/Post)
This class comes from System.Net.Http
namespace
Methods of Class
Most commonly used methods of this class are
- GetAsync
- DeleteAsync
- PostAsync
- PutAsync
Each CRUD method has 4 overloads which serve same purpose with a little bit addition e.g. (Cancellation Token Support )
Dummy API’s and Get Call
Enough talking let’s see the code , there are bunch of free APIs available that contains data over the internet e.g. RestCountriesAPI and PokeAPI , you can use them for retrieving data , for this Newsletter I have used one of my local project and RestCountriesAPI.
HttpClient httpClient = new HttpClient();
string apiURL = "https://restcountries.com/v3.1/region/europe";
var response = await httpClient.GetAsync(apiURL);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
// Deserialize the data into your desired model and use it
}
else
{
Console.Write(response.StatusCode.ToString());
}
After finishing your work you can call Dispose()to free resources
Properties
HttpClient class has some properties that we can set before making HTTP Call.
- Base Address - To set base address one time
- DeafultRequestHeaders - To add media types that are supported
using System.Net.Http.Headers;
HttpClient client = new HttpClient();
string baseAddress = "https://localhost:7265/";
string apiURL = "/api/Dropdown/Categories";
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(apiURL);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
// Deserialize the data into your desired model and use it
}
else
{
Console.Write(response.StatusCode.ToString());
}
On similar pattern you can make Put/Delete and Post Calls
How to use this with Dependency Injection
-
Add the service by
services.AddHttpClient()
,you can set the base address and Default Request headers in service as well . -
After adding service , just inject
IHttpClient
in your desired class and use it.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place