简体   繁体   English

HttpClient和设置授权标头

[英]HttpClient and setting Authorization headers

I'm trying to make a simple request to the Basecamp API , I'm following the instructions provided adding in a sample user agent and my credentials yet I keep getting a 403 Forbidden response back. 我正在尝试向Basecamp API发出一个简单请求,我正在按照提供的说明添加示例用户代理和我的凭据,但仍收到403 Forbidden响应。

My credentials are definitely correct so is it a case of my request/credentials being set incorrectly? 我的凭据绝对正确,是否是我的请求/凭据设置不正确的情况?

This is what I have (removed personal info): 这是我所拥有的(已删除个人信息):

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

A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST: 快速浏览它们的文档似乎表明POST正文中的projects.json端点接受以下内容:

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

You're sending the User-Agent as the POST body. 您正在将User-Agent发送为POST正文。 I'd suggest you change your code as follows: 我建议您按以下方式更改代码:

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

This posts the payload as specified in the docs and sets your user agent in the headers as it should be. 这将按照docs中的规定发布有效负载,并在标题中按原样设置您的用户代理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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