HttpClient并设置授权标头

DGi*_*bbs 9 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());
}
Run Code Online (Sandbox Code Playgroud)

Dea*_*ard 17

快速浏览一下他们的文档似乎表明projects.json端点在POST的主体中接受以下内容:

{
    "name": "This is my new project!",
    "description": "It's going to run real smooth"
}
Run Code Online (Sandbox Code Playgroud)

您正在发送User-AgentPOST主体.我建议您更改代码如下:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

这将按照文档中的指定过帐有效负载,并将用户代理设置在标头中.