HttpClient.GetAsync with network credentials

C#Async Await.Net 4.5

C# Problem Overview


I'm currently using HttpWebRequest to get a website. I'd like to use the await pattern, which is not given for HttpWebRequests. I found the class HttpClient, which seems to be the new Http worker class. I'm using HttpClient.GetAsync(...) to query my webpage. But I'm missing the option to add ClientCredentials like HttpWebRequest.Credentials. Is there any way to give the HttpClient authentication information?

C# Solutions


Solution 1 - C#

You can pass an instance of the HttpClientHandler Class with the credentials to the HttpClient Constructor:

using (var handler = new HttpClientHandler { Credentials = ... })
using (var client = new HttpClient(handler))
{
    var result = await client.GetAsync(...);
}

Solution 2 - C#

You shouldn't dispose of the HttpClient every time, but use it (or a small pool of clients) for a longer period (lifetime of application. You also don't need the handler for it, but instead you can change the default headers.

After creating the client, you can set its Default Request Headers for Authentication. Here is an example for Basic authentication:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "username:password".ToBase64());

ToBase64() represents a helper function that transforms the string to a base64 encoding.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJan K.View Question on Stackoverflow
Solution 1 - C#dtbView Answer on Stackoverflow
Solution 2 - C#JSilvanusView Answer on Stackoverflow