HttpClient and setting Authorization headers

后端 未结 1 1151
北海茫月
北海茫月 2021-01-04 23:13

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

相关标签:
1条回答
  • 2021-01-05 00:12

    A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST:

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

    You're sending the User-Agent as the POST body. 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.

    0 讨论(0)
提交回复
热议问题