31

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?

2
  • 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 8, 2015 at 16:24
  • 1
    @Ananke ok so can you adivce how to change WebClient to be HttpClient ?
    – John John
    Oct 8, 2015 at 17:02

1 Answer 1

45
// Injecting HttpClient would be a better idea if possible
HttpClient client = new();
string page = await client.GetStringAsync("page URL here");
8
  • thanks for the reply,, but will there be any problem if i replace the .Result with await in your code?
    – John John
    Oct 9, 2015 at 15:30
  • 1
    @johnG plz see the updated answer to handle the 'await' instead of 'Result' property. Oct 9, 2015 at 15:45
  • 1
    @johnG I also add an update for the 'WebRequest' class. Oct 9, 2015 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 9, 2015 at 16:46
  • 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. aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong Feb 17, 2019 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.