This article is a mirror article of machine translation, please click here to jump to the original article.

View: 9666|Reply: 7

[Source] ASP.NET Core (XV) uses HttpClient to send HTTP requests

[Copy link]
Posted on 5/14/2022 7:37:21 PM | | | |
When building an application with ASP.NET, an instance of the HttpClient class is used to make an HTTP request. Using HttpClient may seem simple. However, some potential issues are not noticed until the application is under heavy load.

Issues related to the original HttpClient class provided in .NET:The hyperlink login is visible.

HttpClient, while implementing IDisposable, declaring and instantiating it in the using statement is not a preferred operation, becauseWhen releasing an HttpClient object, the underlying socket does notinstantlyrelease, which can cause socket exhaustion issues.

The problem is not really HttpClient itself, but the default constructor of HttpClient, as it creates a new actual HttpMessageHandler instance with the "socket exhaustion" and DNS change issues mentioned above.



Creating HttpClient directly (incorrect use)

Instantiate the HttpClient object directly, and add using to guarantee the call to the Dispose method, the code is as follows:

Call the interface 5 times, send an HTTP request using HttpClient, and check the network connection with the following command:

You can see that when the HttpClient is released, the connection between the local computer and the target server isTIME_WAITIn the case of high concurrency, the error will be reported as follows:

Unable to connect to the remote server
System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted.


For questions, you can also refer to:

Using HttpClinet incorrectly can break your software
https://www.itsvse.com/thread-10310-1-1.html
Create an HttpClinet with IHttpClientFactory (correct usage)

Using DI dependency injection IHttpClientFactory is the same as HttpLinet, which is created using IHttpClientFactory.

Add the service to the Startup file, the code is as follows:

The HomeController controller code is as follows:

We also use HttpClinet to send 5 requests through the call interface, and the machine only establishes a connection with the target server, and the connection is reused during the request process. As shown below:



IHttpClientFactory pools factory-created HttpMessageHandler instances into a pool to reduce resource consumption. When you create a new HttpClient instance, you may reuse the HttpMessageHandler instance in the pool if the lifetime has not expired.

{
    "Lifetime": "Singleton",
    "ServiceType": "System.Net.Http.IHttpClientFactory",
    "ImplementationType": "Microsoft.Extensions.Http.DefaultHttpClientFactory"
  },
  {
    "Lifetime": "Singleton",
    "ServiceType": "System.Net.Http.IHttpMessageHandlerFactory",
    "ImplementationType": "Microsoft.Extensions.Http.DefaultHttpClientFactory"
  }
IHttpClientFactory is implemented by default as DefaultHttpClientFactory, with the source code address:The hyperlink login is visible.

By using IHttpClientFactory in a DI-enabled application, you can avoid:

  • Solve the problem of resource exhaustion by sharing the HttpMessageHandler instance.
  • Resolve DNS staleness by periodically looping through HttpMessageHandler instances.


In addition, there are other ways to solve the above problems using long-lifetime SocketsHttpHandler instances.

  • Create an instance of SocketsHttpHandler at app startup and use it throughout the app's lifecycle.
  • Configure PooledConnectionLifetime to the appropriate value based on the DNS refresh time.
  • Create an instance of HttpClient using new HttpClient(handler, disposeHandler: false) as needed.


The above approach solves resource management problems in a similar way to IHttpClientFactory.

  • SocketsHttpHandler between the HttpClient instancesShared connections。 This sharing prevents socket exhaustion.
  • SocketsHttpHandler loops connections based on PooledConnectionLifetime to avoid DNS staleness.


For more usage and configuration, please refer to:

The hyperlink login is visible.
The hyperlink login is visible.





Previous:Using HttpClient incorrectly can break your software
Next:jQuery Datatables internationalization plugin
 Landlord| Posted on 5/14/2022 7:38:14 PM |
review

ASP.NET Core (fourteen) is based on the SkiaSharp image captcha
https://www.itsvse.com/thread-10287-1-1.html

ASP.NET Core (XIII) to determine whether it is an Ajax request or not
https://www.itsvse.com/thread-10284-1-1.html

ASP.NET Core (twelve) front-end JS, CSS bundling, and compression
https://www.itsvse.com/thread-10282-1-1.html

ASP.NET Core (XI) endpoint route adds middleware to display all DI services
https://www.itsvse.com/thread-10269-1-1.html

ASP.NET Detailed explanation of Configuration priorities in Core(10).
https://www.itsvse.com/thread-10265-1-1.html

ASP.NET Detailed explanation of the Middleware middleware of Core (9).
https://www.itsvse.com/thread-9647-1-1.html

ASP.NET Detailed explanation of Core Middleware
https://www.itsvse.com/thread-8126-1-1.html

ASP.NET pit of the default parameters of the Swagger UI in Core(8).
https://www.itsvse.com/thread-9640-1-1.html

ASP.NET Core (7) In-depth analysis of the framework source code
https://www.itsvse.com/thread-9601-1-1.html

ASP.NET Core (VI) DI manually obtains the method of injecting objects
https://www.itsvse.com/thread-9595-1-1.html

ASP.NET Core (five) is based on CAP distributed transactions
https://www.itsvse.com/thread-9593-1-1.html

ASP.NET Core(4) filter unified ModelState model validation
https://www.itsvse.com/thread-9589-1-1.html

ASP.NET Core (iii) Dynamically create instances using ActivatorUtilities
https://www.itsvse.com/thread-9488-1-1.html

ASP.NET Core (2) Restart the application by code
https://www.itsvse.com/thread-9480-1-1.html

ASP.NET Core (1) uses Redis caching
https://www.itsvse.com/thread-9393-1-1.html
 Landlord| Posted on 5/14/2022 7:41:13 PM |
Posted on 5/14/2022 10:36:06 PM |
Learn it
Posted on 5/19/2022 9:45:12 AM |
Here it comes, check out the sequel
Posted on 8/18/2022 4:13:45 PM |
Awesome learning and learning
 Landlord| Posted on 6/24/2023 1:07:32 PM |
.NET/C# HttpClient source code simple analysis
https://www.itsvse.com/thread-10617-1-1.html
 Landlord| Posted on 9/5/2024 2:35:55 PM |
Check out the HttpClientFactoryServiceCollectionExtensions source code

The default implementation of IHttpClientFactory isDefaultHttpClientFactory, as shown in the figure below:



The CreateClient method in DefaultHttpClientFactory instantiates the HttpClient objectdisposeHandler: false, as shown in the figure below:



Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com