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 advice how I can change it from WebClient to be HttpClient?
The HttpWebRequest class provides a lot of control over the request/response object. However, you should be aware that HttpClient was never designed to be a replacement for WebClient. You should use HttpWebRequest instead of HttpClient whenever you need the additional features that HttpWebRequest provides.
Starting in . NET 6, the WebRequest, WebClient, and ServicePoint classes are deprecated. The classes are still available, but they're not recommended for new development. To reduce the number of analyzer warnings, only construction methods are decorated with the ObsoleteAttribute attribute.
WebClient is just a wrapper around HttpWebRequest, so it uses HttpWebRequest internally. The WebClient bit slow compared to HttpWebRequest. But is very much less code. we can use WebClient for simple ways to connect and work with HTTP services.
You can write the following code:
string url = 'some url';
// best practice to create one HttpClient per Application and inject it
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
}
}
Update 1 :
if you want to replace the calling to Result
property with the await
Keyword, then this is possible, but you have to put this code in a method which marked as async
as following
public async Task AsyncMethod()
{
string url = 'some url';
// best practice to create one HttpClient per Application and inject it
HttpClient client = new HttpClient();
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
var json = await content.ReadAsStringAsync();
}
}
}
if you missed the async
keyword from the method, you could get a Compile-time error like the following
The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<System.Threading.Tasks.Task>'.
Update 2 :
Responding to your original question about converting the 'WebClient' to 'WebRequest' this is the code that you could use, ... But Microsoft ( and me ) recommended you to use the first approach (by using the HttpClient).
string url = currentURL + "resources/" + ResourceID + "/accounts?AUTHTOKEN=" + pmtoken;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
using (WebResponse response = httpWebRequest.GetResponse())
{
HttpWebResponse httpResponse = response as HttpWebResponse;
using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream()))
{
var json = reader.ReadToEnd();
}
}
if you use C# 8 and above, then you can write very elegant code
public async Task AsyncMethod()
{
string url = 'some url';
// best practice to create one HttpClient per Application and inject it
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
var json = await content.ReadAsStringAsync();
} // dispose will be called here, when you exit of the method, be aware of that
Update 3
To know why is HttpClient
is more recommended than WebRequest
and WebClient
you can consult the following links.
Deciding between HttpClient and WebClient
http://www.diogonunes.com/blog/webclient-vs-httpclient-vs-httpwebrequest/
HttpClient vs HttpWebRequest
What difference is there between WebClient and HTTPWebRequest classes in .NET?
http://blogs.msdn.com/b/henrikn/archive/2012/02/11/httpclient-is-here.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With