为什么创建令牌时会创建错误

why An error is created when creating the token

 public static void CreateToken()
    {

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("grant_type", "client_credentials");
        var UserPassJson = "{\"username\": \"mucode\",\"password\": \"mypassword\"}";

        HttpContent content = new StringContent(UserPassJson, Encoding.UTF8, "application/json");

        var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
        if (response.IsSuccessStatusCode)
        {
            var responseContent = response.Content;
            string responseString = responseContent.ReadAsStringAsync().Result;
            Console.WriteLine(responseString);
        }
    }

为什么 response.IsSuccessStatusCode 显示状态代码 401?是什么原因导致故障? 什么动作会导致成功?

documentation specifies that you should pass the username and password using basic authentication 并且你应该传递包含 grant_type=client_credentials.

的 form-encoded body

目前您的代码将 grant_type 添加为 header,并将用户名和密码作为 JSON object 发布在 body 中。

按照文档说明的方式更正您的代码,我们得到:

HttpClient client = new HttpClient();
byte[] authBytes = System.Text.Encoding.ASCII.GetBytes("mucode:mypassword");
string base64Auth = Convert.ToBase64String(authBytes);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64Auth);

HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("grant_type", "client_credentials") });

var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
if (response.IsSuccessStatusCode)
{
    var responseContent = response.Content;
    string responseString = responseContent.ReadAsStringAsync().Result;
    Console.WriteLine(responseString);
}

P.S。我推荐阅读You're using HttpClient wrong and it is destabilizing your software and the follow-up You're (probably still) using HttpClient wrong and it is destabilizing your software。我还建议使用此方法 async 并使链条一直向上 async