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