从“授权 API”获取 FedEx oAuth 令牌

问题描述 投票:0回答:0

当我从 Postman 创建 Post 请求时,我可以获得 Fedex“access_token”。我将“client_id”和“client_secret”添加到请求正文中,如文档 (Fedex) 中给出的原始字符串。

确切的PostMan C#代码如下:

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://apis-sandbox.fedex.com/oauth/token");
request.Headers.Add("content-type", "application/x-www-form-urlencoded");
request.Headers.Add("Cookie",.......some cookie....");
var content = new StringContent("grant_type=client_credentials&client_id=...clientid...&client_secret=....client secret.....", null, "application/x-www-form-urlencoded");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();

当我在 Visual Studio 中使用此代码进行测试时,

request.Headers.Add("content-type", "application/x-www-form-urlencoded");
我收到错误消息:

Misused header name, 'content-type'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.'

搜索答案后,我将代码还原为:

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://apis-sandbox.fedex.com/oauth/token");
HttpContent content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("client_id", "...clientid..."),
new KeyValuePair<string, string>("client_secret", "..client secret....."),
new KeyValuePair<string, string>("grant_type","client_pc_credentials")});
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
content.Headers.ContentType.CharSet = "UTF-8";
client.DefaultRequestHeaders.ExpectContinue = false;
HttpResponseMessage response = await client.PostAsync(new Uri("https://apis-sandbox.fedex.com/oauth/token"), content);
        
return await response.Content.ReadAsStringAsync();

我像

var oAuth = MakeApiCallAsync();
这样调用这个方法这段代码运行没有错误,但它没有到达最后一行代码(
return await response.Content.ReadAsStringAsync();
)并且流程继续到调用方法并且变量oAuth获取值(Result = Yet not计算,.....其他属性)

我尝试了几乎所有的方法,我已经筋疲力尽了,有什么想法是错的吗?

asp.net-core httprequest
© www.soinside.com 2019 - 2024. All rights reserved.