Hi i am trying to call basic authentication in wpf httpclient. however whenever i run the code nothing is showing. Can someone help me why? I am new. Thank you
This is the code:
var userName = "username";
var passwd = "password";
var url = "url";
using var client = new HttpClient();
var authToken = Encoding.ASCII.GetBytes($"{userName}:{passwd}");
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authToken));
var result = await client.GetAsync(url);
var content = await result.Content.ReadAsStringAsync();
label1.Content = content;
Add content type json since you are returning json. And you have to deserialize your content after receiving
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);
// instead of object it is better to use a class you are expecting from request
} else ...error
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.