简体   繁体   中英

c# How do I add 'Authorization: Basic' to my HttpClient header?

I'm trying to send GET method to a web REST api and it requires authorization in this form:

Authorization: Basic <Base64 value of UTF-8 encoded “username:password”>

This request gives me:

Response status code does not indicate success: 401 (Unauthorized).

Code:

try
{
    var client = new HttpClient();
    client.BaseAddress = bUrl; // https url
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-type", "application/xml");
    client.DefaultRequestHeaders.Add("Authorization", "Basic " + uAuth);
    HttpResponseMessage XmlResponse = await client.GetAsync(url);
    XmlResponse.EnsureSuccessStatusCode();

    string xml = await XmlResponse.Content.ReadAsStringAsync();
    Debug.WriteLine(xml);
}
catch (HttpRequestException hre) {
    Debug.WriteLine(hre.ToString());
} catch (Exception ex) {
    Debug.WriteLine(ex.ToString());
}

While uAuth is just a Base64 Username:Password representation:

string uAuth =
            Convert.ToBase64String(
            Encoding.UTF8.GetBytes("username:password")
            );

Am I doing something wrong?

edit: Tried also with:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", uAuth);

您可以使用DefaultRequestHeaders上的Authorization属性:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", uAuth);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM