112

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?

2 Answers 2

186

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(...);
}
7
  • 22
    You can also set UseDefaultCredentials = true for HttpClientHandler Jan 26, 2014 at 14:13
  • 9
    This can cause suboptimal behavior when Basic authentication is required stackoverflow.com/q/25761214/57428
    – sharptooth
    Sep 10, 2014 at 9:38
  • 2
    i've found you will want to set handler.ClientCertificateOptions = ClientCertificateOption.Automatic in order to actually have the credititals sent.
    – Geoduck
    Feb 29, 2016 at 0:10
  • 6
    Its advisable to use a static instance of HttpClient, especially in server scenarios Jul 27, 2017 at 13:26
  • 3
    So what should we do in server scenarios? We are running in to the issues that you have when you don't have a static instance but we need to pass in credentials. Sep 7, 2017 at 14:56
8

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.

1
  • 1
    this way works much better when using a HttpClientFactory, allows you to easily use the same httpClient with different credentials without creating a new handler each time.
    – dove
    Jan 11, 2022 at 11:20

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.