0

I have an existing library which I am adapting to use the new HttpClient in .NET 4.5. The library allows sending HTTP requests with differing configuration options for all requests i.e. properties like Timeout, AllowAutoRedirect and Proxy can be set differently.

This was relatively easy with HttpWebRequest, but that had its own issues (Like annoying restricted headers).

To my understanding, properties such as these must now be set in a HttpRequestHandler and passed onto the HttpClient constructor; And the HttpClient is designed to be reused across the entire application.

How could I set my requests up such that this would be possible?

Hele
  • 1,558
  • 4
  • 23
  • 39

1 Answers1

1

How could I set my requests up such that this would be possible?

One possible way is to have an HttpClient instance per different request strategy (Timeout, AllowAutoRedirect and Proxy).

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Yes, but the modifiable properties are many more than listed, and maintaining one instance for each combination would be too inefficient. – Hele Jan 12 '17 at 15:32
  • Well, I am afraid that in this case you will need to have a separate instance of `HttpClient` which might not be the most efficient way indeed. – Darin Dimitrov Jan 12 '17 at 15:34
  • Okay, so keeping your comment in mind, I took a look at the RestSharp library. It appears to also have a similar concept of XxClient. Would you know if RestClient is lighter than HttpClient or vice versa? (If you prefer, I could move this to a new question). – Hele Jan 12 '17 at 16:09
  • As far as I know RestSharp uses HttpWebRequest internally: https://github.com/restsharp/RestSharp/blob/master/RestSharp/RestRequestAsyncHandle.cs. So it can't really be compared to `HttpClient` and it doesn't need to be a singleton instance. – Darin Dimitrov Jan 12 '17 at 16:12
  • Okay, I just ran a test and the results are blinding. Creating 30k instances of HttpClient take roughly 30ms whereas creating 30k instances of RestClient take about 21000ms. Thanks for your help! (Also, according to http://stackoverflow.com/questions/20530152/need-help-deciding-between-httpclient-and-webclient , `HttpClient` _also_ uses `HttpWebRequest` internally). – Hele Jan 12 '17 at 16:25
  • Yes, HttpClient also uses HttpWebRequest internally but the results of using a single instance of HttpClient vs many instances are also blinding :-) Since I have switched to to singleton HttpClient instances I can see a net gain of performance. – Darin Dimitrov Jan 12 '17 at 16:27
  • I'll keep that in mind. I plan to create new instances every time, _but_ also design an alternate class which retains the `HttpClient` across requests. I'll leave a note in the documentation recommending the usage of this new class instead. – Hele Jan 12 '17 at 16:31