Friday, September 6, 2019

HttpClient - a closer look (C#.Net)

HttpClient is the new and improved way of doing HTTP requests and posts, having arrived with .Net Framework 4.5. It provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
HttpClient is preferred over HttpWebRequest due to async methods available out of the box and you would not have to worry about writing begin/end methods. Basically when you use async call (using either of the class), it will not block the resources waiting for the response and any other request would utilize the resources to make further calls. Another thing to keep in mind that you should not be using HttpClient in the 'using' block to allow reuse of same resources again and again for other web requests.
Recommend use:
  • If all the operations for a service share the same set of default headers, then have an instance of HttpClient for each endpoint that your application is communicating to.
  • If an endpoint requires different header for each HTTP method, then you’ll need to create an instance of HttpClient for each combination of verb+ endpoint.
These client classes should be made Singleton across the application or the HttpClient variable should be declared private static readonly within the Client class. This will allow you to:
  • Benefit from the performance optimizations provided by connection pooling;
  • Avoid running out of available ports due to connections in TIME_WAIT state if the server gets heavy load;
  • Use default BaseAddress and HTTP Headers for each service your application integrates to
If you are getting either below errors, you may need to check the default security protocol used by HttpClient:
  • One or more errors occurred.
  • An error occurred while sending the request.
  • The underlying connection was closed: An unexpected error occurred on a receive.
  • The client and server cannot communicate, because they do not possess a common algorithm.
To resolve this issue, you can use:
using System.Net;
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
As,
  • It needed for .Net 4.5 because Tls12 is not a default protocol.
  • You need to write the above code only once within the application. (For example within Global.asax > Application_Start within Web application or equivalent in Winforms application)
  • For .Net 4.6 and above, Tls12 is a default protocol so it is not needed.