Home > database >  .NET 6 Using HTTP Client for API Calls within Web API Project Controllers
.NET 6 Using HTTP Client for API Calls within Web API Project Controllers

Time:10-14

I am still new to .NET and have been using HttpClient to do calls to other APIs within my API controllers. According to this article, I should only have one HttpClient instance because it causes a socket exhaust error.

However, I am currently creating one HttpClient per API controller. Should I make a static utility class instead that contains the single HttpClient or should I keep what I have? Is there a better alternative or a best practice when working with API controllers that themselves call other APIs?

If more information is required, please let me know.

CodePudding user response:

The method recommended to use httpclient is to use IHttpClientFactory and Dependency Inject.

Using the IHttpClientFactory has several benefits, including managing the lifetime of the network connections. Using the factory to create the client reuses connection from a connection pool, thereby not creating too many sockets. The connections are reused and automatically disposed to avoid DNS level issues.

By using IHttpClientFactory, we can solve all the initial issues that we saw with instantiating the HttpClient instance directly. After refactoring it to the Typed client consumption pattern, it is also well separated and easier to maintain. It drives us to write cleaner, loosely coupled code.

You can read these two articles(1, 2) to learn more.

  • Related