HttpClient并设置授权标头

时间:2014-07-07 11:33:23

标签: c# authentication httpclient

我正在尝试向Basecamp API发出一个简单的请求,我正按照提供的说明添加示例用户代理和我的凭据,但我仍然收到403 Forbidden响应。

我的凭据绝对正确,所以我的请求/凭据设置不正确吗?

这就是我所拥有的(删除了个人信息):

var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") });

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));

var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);
var responseContent = response.Content;

using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
     Console.WriteLine(await reader.ReadToEndAsync());
}

1 个答案:

答案 0 :(得分:17)

快速查看他们的文档似乎表明projects.json端点在POST正文中接受以下内容:

{
    "name": "This is my new project!",
    "description": "It's going to run real smooth"
}

您正在发送User-Agent作为POST正文。我建议您更改代码如下:

    var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
        var response = await httpClient.PostAsJsonAsync(
            "https://basecamp.com/[USER ID]/api/v1/projects.json",
            new {
                name = "My Project",
                description = "My Project Description"
            });

        var responseContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseContent);
    }

这会按照文档中的规定发布有效负载,并将用户代理设置在标头中。