如何调用RESTful服务并传入基本身份验证。这是用户名和密码以及授权基本。
using (var httpClient = new HttpClient())
{
//var request = new StringContent(messageBody);
//request.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpClient.BaseAddress = new Uri(serviceUrl);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var credentials = Encoding.ASCII.GetBytes("myadmin:mypassword");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
//var response = await httpClient.PostAsJsonAsync(serviceUrl, customer);
HttpResponseMessage response = await httpClient.PostAsJsonAsync("url here", customer);
}
答案 0 :(得分:0)
您必须使用冒号连接用户名和密码,将值编码为base64,然后使用“基本”方案将此值添加到Authorization标头。