Yes, see MSDN samples : HttpClient
Although I still use HttpWebRequest in some cases when HttpClient freezes, even if MS says
"We don't recommend that you use HttpWebRequest for new development. Instead, use the System.Net.Http.HttpClient class."
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi,
I want to ask. is enough to have:
private static readonly HttpClient Client;
in order to have the best performance? or there is more to do?
Thanks,
Jassin
Yes, see MSDN samples : HttpClient
Although I still use HttpWebRequest in some cases when HttpClient freezes, even if MS says
"We don't recommend that you use HttpWebRequest for new development. Instead, use the System.Net.Http.HttpClient class."
Performance wise, and also for simple console apps (particularly if they aren't long-running), creating a single HttpClient
is perfectly fine.
If you have a long-running app then you're still fine with regard to performance, although the underlying HttpMessageHandler
(the component of HttpClient
that manages the connection) won't be aware of any DNS changes that occur during the lifetime of the object.
It's preferred that rather than creating HttpClient
instances yourself, you use a factory instead, which will substitute out the HttpMessageHandler
whenever an instance of HttpClient
is produced via it. This would typically be configured when registering your services with the AddHttpClient
method.
This article goes through this in detail:
[https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-net
There are some caveats to be aware of as it depends on what you later do with that client. Be aware of sockets exhaustion (although you are using a static field, so this shouldn't be a problem) and changing DNS'. In general, it is recommended to use the same base URL for a single HttpClient
instance throughout the lifetime of the application. Using an IHttpClientFactory helps to avoid common pitfalls with HTTP clients.