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
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(...);
}
-
22You can also set
UseDefaultCredentials = true
forHttpClientHandler
Jan 26, 2014 at 14:13 -
9This can cause suboptimal behavior when Basic authentication is required stackoverflow.com/q/25761214/57428 Sep 10, 2014 at 9:38
-
2i've found you will want to set handler.ClientCertificateOptions = ClientCertificateOption.Automatic in order to actually have the credititals sent.– GeoduckFeb 29, 2016 at 0:10
-
6Its advisable to use a static instance of HttpClient, especially in server scenarios Jul 27, 2017 at 13:26
-
3So 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
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.
-
1this 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.– doveJan 11, 2022 at 11:20