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

时间:2020-02-06 07:23:04

标签: c# asp.net api httpclient access-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?是什么原因导致故障? 什么动作会导致成功?

1 个答案:

答案 0 :(得分:0)

documentation指定您应使用basic authentication传递用户名和密码,并且应传递包含grant_type=client_credentials的表单编码正文。

此刻,您的代码将grant_type添加为标头,并将用户名和密码作为JSON对象发布在正文中。

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

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和后续内容You're (probably still) using HttpClient wrong and it is destabilizing your software。我还建议采用这种方法async,并使链条也一直向上async