HTTP Requests In ASP.NET Core

Making HTTP Requests in ASP.NET Core

In this article, we will discuss how to call a Restful API using `HttpClient` in ASP.NET Core. For a comprehensive understanding of HTTP, please refer to our article on HTTP Protocol.

Before calling any API, it is essential to gather some information:

HTTP, short for Hyper-Text Transfer Protocol, is an application layer protocol used for exchanging resources between a client and a server.

URL

The endpoint URL.

HTTP Method

Whether it is POST, GET, or another method.

Request Data

What data is sent in the request, such as Body, Header Parameter, Query Parameter, Fragment, or URL Parameter.

Authorization

If the API requires authorization, how it should be sent (e.g., via Header).

Certification

Sometimes encryption and decryption certificates are needed, especially for financial systems.

Response Data

Understanding the response data type (e.g., XML or JSON) and handling it accordingly.

Using HttpClient

Here’s a basic example of using HttpClient:

In this example, we:

  • Create an instance of `HttpClient`. 
  • Specify the URI and HTTP Method.
  • Call the API.
  • Convert the response body to a string (optional but useful).

Disadvantages of This Approach

This method can lead to performance issues when handling many requests, as it can cause memory problems.

Recommended Approaches

To improve performance, we can use dependency injection (DI) with the following approaches:

  • Basic Usage
  • Named Client
  • Typed Client
  • Generated Client

Basic Usage

Register `IHttpClientFactory` using `AddHttpClient` in the Dependency Injection container. This interface is available in ASP.NET Core, and `AddHttpClient` adds it as a singleton service.

Then request `IHttpClientFactory` from Dependency Injection:

Named Client

In this method, we assign a name to the `HttpClient` when registering the service:

Use this name when calling the client in Dependency Injection:



Typed Client

This method simplifies the process by avoiding the use of strings in DI and `CreateClient`, offering additional benefits like method definitions and better IntelliSense support. 

Register in the Dependency Injection container:

Call the service by name:

Generated Client

  • Generated clients are created at runtime and are often used with Refit
  • Create an interface for `HttpClient` with endpoints as methods
  • Each method has its own parameters and Return Type
  • The Parameter belongs to a Request and consists of Header and Body
  • The Return Type belongs to Response
  • The Attribute belongs to URI

Register this interface:

Call the interface in the same way we did previously in the required service or controller

Refer to  Refit for more information on this NuGet package.

Testing APIs

It is often useful to test these APIs before writing code to understand and handle the API response easily. Tools like Postman can be used for this purpose.

Blogs Related