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.

How to use HTTP Client in C#

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

How to use HTTP Client in C#

On similar pattern you can make Put/Delete and Post Calls

How to use this with Dependency Injection

  1. Add the service by services.AddHttpClient(),you can set the base address and Default Request headers in service as well .

  2. After adding service , just inject IHttpClient in your desired class and use it.

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place