c#如何在我的HttpClient标题中添加'Authorization:Basic'?

时间:2014-07-24 12:42:29

标签: c# asp.net rest

我试图将GET方法发送到Web REST api,它需要以这种形式授权:

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

这个请求给了我:

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

代码:

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());
}

虽然uAuth只是Base64 Username:Password代表:

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

我做错了吗?

编辑: 也试过:

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

1 个答案:

答案 0 :(得分:2)

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

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", uAuth);
相关问题