HttpClient和设置授权头

本文关键字:授权 设置 HttpClient | 更新日期: 2023-09-27 18:11:50

我正试图向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());
}

HttpClient和设置授权头

快速浏览他们的文档似乎表明项目。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);
    }

按照文档中指定的方式发布有效负载,并在header中设置用户代理。