URL中的HttpClient和Basic Auth

问题描述 投票:0回答:1

我想通过在URL中指定用户名和密码来使用HttpClient和HTTP basic auth,如下所示:

var request = new HttpRequestMessage(HttpMethod.Get, 
    "https://username:[email protected]");

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

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

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

.net basic-authentication dotnet-httpclient
1个回答
2
投票

您需要设置标头,而不是通过URL传递它

var byteArray = Encoding.ASCII.GetBytes("username:password1234");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
© www.soinside.com 2019 - 2024. All rights reserved.