1024programmer Asp.Net The correct way to use HttpClient in .NET Core

The correct way to use HttpClient in .NET Core

The correct way to use HttpClient in .NET Core

Foreword

HttpClient is a class in .NET Framework, .NET Core or .NET 5 and above, used to send HTTP requests to Web API and receive responses. It provides some easy-to-use methods, such as GET, POST, PUT, and DELETE, to easily construct and send HTTP requests, and process response data. It is an official HTTP request component that we commonly use, so are you using it correctly? This article will explore the correct use of HttpClient.

Environment preparation

First, we use vs2022 to create a Web API application with the default WeatherForcast template, and a common API program. The project uses .NET6.

The project structure is as follows

Function points of the two projects:

HttpClientTest – Web API that returns weather forecast

HttpClientTest2 – This project will use HttpClient to request the weather preparation of HttpClientTest.

Next, we use 4 methods to illustrate the correct use of HttpClient.

Method 1

We first create the HttpClientTestController class in HttpClientTest2, and write a method to request weather preparation, the code is as follows:

namespace HttpClientTest2.Controllers
 {
     [Route("api/[controller]")]
     [ApiController]
     public class HttpClientTestController : ControllerBase
 {
         [HttpGet]
         public async Task TestHttpClient()
         {
 var url = "https://localhost:7281/WeatherForecast";
             #region version 1
 var httpClient = new HttpClient();
   var response = await httpClient. GetAsync(url);
   return await response.Content.ReadAsStringAsync();
 #endregion
 }
 }
 }  
 

After the code is written, we set up multi-project startup so that these two projects start at the same time.

Picture

After the project starts, execute the TestHttpClient request interface of the project HttpClientTest2. Do it several times. Mainly look at the implementation of the HttpClient background. Here you can use netstat to check http requests.

Open a CMD console program. Enter the following code:

netstat -na | find "7281"
 

Port 7281 is our request site HttpClientTest. The effect of multiple clicks is as follows:

It can be seen from the above that there are multiple requests, indicating that the request is not closed. Then change to the second method.

Method 2

Use the using command to realize the end of the request and close the request, the code is as follows:

 #region version 2
     using (var httpClient = new HttpClient())
    {
         var response = await httpClient. GetAsync(url);
         return await response.Content.ReadAsStringAsync();
    }
    #endregion
    //Welcome to the official account: DOTNET development job hopping
 

Similarly, we have requested many times, and the result is as follows:

You can see the status “TIME_WAIT” here, indicating that the link has been closed, but the actual link still occupies the port and will be released when the resources are exhausted. This is the problem with socket connections. Socket exhaustion means that all available socket resources on the server have been fully occupied and cannot provide services for new connections. In TCP/IP network communication, at most one connection can be established on each port, which limits the number of connections the server can handle. When the server load is too high, it may cause socket resources to be tight, which in turn leads to socket exhaustion. For the above problems, continue to improve HttpClient.

Method 3

Here we use the singleton pattern to try. The code is as follows:

public class HttpClientTestController : ControllerBase
     {
 private static HttpClient _httpClient;
   static HttpClientTestController()
 {
 _httpClient = new HttpClient();
 }
 // Note: There are many ways to implement the singleton pattern.  A static instance method is used here.
         [HttpGet]
         public async Task TestHttpClient()
         {
 var url = "https://localhost:7281/WeatherForecast";
             #region version 3
             //var response = await _httpClient. GetAsync(url);
             //return await response.Content.ReadAsStringAsync();
 #endregion
         }
     }
 

After the code is written, let’s try again, the result is as follows:

picture

Because the singleton pattern is used, no new instance is created using the same connection. This approach solves the socket exhaustion problem. However, we noticed that there was an open connection with status “established”. If there are DNS changes or network related changes that may affect the connection, the application may fail requiring an application restart to resolve. This method is also suboptimal.

Method 4

HttpClient is a .NET built-in method, which can be implemented by using the IHttpClientFactory interface to avoid the above problems. The code is as follows:

public class HttpClientTestController : ControllerBase
 {
         private readonly IHttpClientFactory _httpClientFactory;
         public HttpClientTestController(IHttpClientFactory httpClientFactory)
         {
             _httpClientFactory = httpClientFactory;
 }
         [HttpGet]
         public async Task TestHttpClient()
         {
 var url = "https://localhost:7281/WeatherForecast";
             #region version 4
             var httpClient = _httpClientFactory. CreateClient();
             var response = await httpClient. GetAsync(url);
             return await response.Content.ReadAsStringAsync();
 #endregion
         }
 //Welcome to the official account: DOTNET development job hopping
 

If you use IHttpClientFactory, you need to inject it in Program.cs, the code is as follows:

builder.Services.AddHttpClient();
 

The same request multiple times, and then execute the netstat command. The effect is as follows:

image

From the status of the request, the problem is solved perfectly by using _httpClientFactory.CreateClient().

Conclusion

This paper uses four methods to gradually describe the use of HttpClient and the problems in the process of use, and finally uses IHttpClientFactory to solve the problems that arise. I hope this article has gained something for you, welcome to leave a message or complain.

Source address: https://github.com/xbhp/webapitest

Reference: Microsoft Official Document

Source public account: DotNet development job hopping
 
This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/the-correct-way-to-use-httpclient-in-net-core/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索