URL中的HttpClient和Basic Auth

时间:2018-03-05 08:48:41

标签: .net basic-authentication dotnet-httpclient

我想通过在URL中指定用户名和密码来使用HttpClient和HTTP基本身份验证,如下所示:

var request = new HttpRequestMessage(HttpMethod.Get, 
    "https://username:password@example.com");

using (var client = new HttpClient()) {
    await client.SendAsync(request);
}

但是,请求没有发送Authorization标头。

有没有办法告诉HttpClient支持这个,还是我必须手动从URL获取凭据并自己设置标题?

1 个答案:

答案 0 :(得分:3)

您需要设置标头,而不是通过网址

传递标头
var byteArray = Encoding.ASCII.GetBytes("username:password1234");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));