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
Some useful 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
Promote yourself to 1650+ subscribers by sponsoring my newsletter (Reach me at mwaseemzakir@gmail.com)
Become a Patron and get access to 100+ .NET Questions and Answers
Download my eBook from Gumroad that contains 30 .NET Tips
Thanks for your useful post.
I want to suggest a useful extension that helps us know what we send for providers or external services exactly. It's called The HttpClientToCurl :
https://github.com/amingolmahalle/HttpClientToCurlGenerator