filmov
tv
.NET Core HttpClient Best Practices Every Developer Should Know About | HOW TO - Code Samples

Показать описание
#coding #codingbootcamp #softwaredeveloper #CodeYourFuture
The following are a set of best practices for using the HttpClient object in .NET Core when communicating with web APIs. Note that probably not all practices would be recommended in all situations. There can always be good reasons to break from a certain practice.
This list is not supposed to be exhaustive and will probably be edited over time.
Manage HttpClient instances with HttpClientFactory
HttpClient implements IDisposable. However, unlike most disposable types in .NET the HttpClient should rarely be explicitly disposed.
When we dispose of the HttpClient the underlying HttpClientHandler is also disposed and the connection is closed. Any additional requests mean the connection must be reopened. Re-opening connections is a slow and costly operation and may even lead to socket exhaustion.
However, if a HttpClientHandler is never disposed (and it’s connection is never closed) it leads us to a different problem: not honouring changes in DNS. This reusing of the connection can lead our HttpClient to make requests to the wrong server.
To help with these two problems .NET Core (2.1+) provides the HttpClientFactory to help when instantiating instances of HttpClient. When the factory is called to create an instance of HttpClient the underlying HttpClientHandler is taken from a pool. Handlers exist in the pool for a default of 2 minutes before they are disposed. This means the connection closing/re-opening problem is mitigated while at the same time honouring changes in DNS.
Use SendAsync
Instead of the particular HTTP verb based shortcut methods on HttpClient (such as GetAsync, PostAsync etc.) use the SendAsync method.
This method allows you to create a particular request object (HttpRequestMessage) that is then passed to the method.
There are two main benefits to using a HttpRequestMessage in conjunction with SendAsync:
It allows more specific control over the request that might not be possible using the HTTP verb style shortcut methods.
Headers can be placed on the individual request rather than on the HttpClient itself. A HttpClient instance should be shared across requests so any default headers set on the client will be used for all requests the HttpClient performs. In most circumstances this is not a good idea as the same HttpClient instance could be potentially used to perform different types of requests, to different endpoints, with different headers etc.
Lots of Great How Tos and Code Samples! Make sure to like and subscribe!