具有网络凭证的 HttpClient.GetAsync

我目前使用 HttpWebRequest得到一个网站。我想使用等待模式,这是没有给出的 HttpWebRequests。我找到了类 HttpClient,它似乎是新的 Http 工作类。我使用 HttpClient.GetAsync(...)查询我的网页。但是我错过了像 HttpWebRequest.Credentials那样添加 ClientCredentials的选项。有没有办法提供 HttpClient身份验证信息?

100552 次浏览

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(...);
}

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.