Best practices for System.Net classes
The following recommendations will help you use the classes contained in System.Net to their best advantage:
For Transport Layer Security (TLS) best practices, see Transport Layer Security (TLS) best practices with .NET Framework.
Use HttpClient to send HTTP requests instead of WebRequest, which was obsoleted in .NET 6. In .NET Framework, create a new
HttpClientinstance each time you need to send a request. (The guidance for .NET 5+/.NET Core is more nuanced. For more information, see Guidelines for using HttpClient.)
The number of connections opened to an internet resource can have a significant impact on network performance and throughput. System.Net uses two connections per application per host by default. Setting the ConnectionLimit property in the ServicePoint for your application can increase this number for a particular host. Setting the ServicePointManager.DefaultPersistentConnectionLimit property can increase this default for all hosts.
When writing socket-level protocols, try to use TcpClient or UdpClient whenever possible instead of writing directly to a Socket. These two client classes encapsulate the creation of TCP and UDP sockets without requiring you to handle the details of the connection.
When accessing sites that require credentials, use the CredentialCache class to create a cache of credentials rather than supplying them with every request. The CredentialCache class searches the cache to find the appropriate credential to present with a request, relieving you of the responsibility of creating and presenting credentials based on the URL.
Submit and view feedback for