我想通过在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获取凭据并自己设置标题?
您需要设置标头,而不是通过URL传递它
var byteArray = Encoding.ASCII.GetBytes("username:password1234");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));