30

I have the following WebClient inside my asp.net mvc web application:

using (WebClient wc = new WebClient()) // call the Third Party API to get the account id 
{
     string url = currentURL + "resources/" + ResourceID + "/accounts?AUTHTOKEN=" + pmtoken;
     var json = await wc.DownloadStringTaskAsync(url);
 }

So can anyone advise how I can change it from WebClient to be HttpClient?

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
John John
  • 1
  • 72
  • 238
  • 501
  • 5
    All the cool kids are using HttpClient now. This is a wrapper around WebRequest and provides an easier model to work with. – Ananke Oct 08 '15 at 16:24
  • 1
    @Ananke ok so can you adivce how to change WebClient to be HttpClient ? – John John Oct 08 '15 at 17:02

1 Answers1

43
// Injecting HttpClient would be a better idea if possible
HttpClient client = new();
string page = await client.GetStringAsync("page URL here");
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
  • thanks for the reply,, but will there be any problem if i replace the .Result with await in your code? – John John Oct 09 '15 at 15:30
  • 1
    @johnG plz see the updated answer to handle the 'await' instead of 'Result' property. – Hakan Fıstık Oct 09 '15 at 15:45
  • 1
    @johnG I also add an update for the 'WebRequest' class. – Hakan Fıstık Oct 09 '15 at 16:00
  • thanks for the reply,, but why it is recommended to use HttpClient, i did not get your point .. thanks ... – John John Oct 09 '15 at 16:46
  • @johnG I updated the answer, please consider this answer as accepted if it is really solve your problem. – Hakan Fıstık Oct 09 '15 at 16:57
  • 7
    Wrapping `HttpClient` in a `using` block is bad. Please don't do this. See the link below for a detailed explanation of why. Long story short, `HttpClient` was designed to be used as a single instance throughout your application. It handles opening and closing sockets for you. By wrapping it in a `using` block, it gets disposed after, and won't close the socket like it's supposed to. This can result in the system running out of sockets once a certain threshold of requests per second is met. https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ – Anthony Stivers Feb 17 '19 at 11:41
  • @AnthonyStivers absolutely true. it defeats the purpose. – SRIDHARAN Oct 13 '20 at 11:56
  • I think any class that implements IDisposable should be kept in a using block and that everything else should result in a compilation error. If HttpClient wants to do some smart socket reuse, it can still do so by not disposing everything in the Dispose method. – Anders Lindén Nov 23 '20 at 09:44