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.
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
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