簡體   English   中英

在 C# 中創建 Postman 請求

[英]Creating Postman request in C#

我可以在 Postman 中提出以下請求,但不能在 C# 中提出。我猜這是由於 json 造成的,但嘗試了幾種不同的方法,但仍然一無所獲。

Postman:

curl --location --request POST 'https://login.sandbox.payoneer.com/api/v2/oauth2/token' \
--header 'Authorization: Basic *ENCRYPTEDPASSCODE FROM ClientID & Secret*' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'scope=read write'

我的代碼返回文本“ErrorParams”:null:

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"https://login.sandbox.payoneer.com/api/v2/oauth2/token");

var authString = $"{clientID}:{secret}";
var encodedString = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(authString));

request.Headers.Add("Authorization", $"Basic {encodedString}");

string json = JsonConvert.SerializeObject(new
{
    grant_type = "client_credentials",
    scope = "read write"
});

request.Content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");

var response = await client.SendAsync(request).ConfigureAwait(false);
var responseText = await response.Content.ReadAsStringAsync();

return responseText;

如果將請求體序列化為 JSON,則需要將Content-Type設置為application/json

request.Headers.Add("Content-Type", "application/json");

如果您需要將內容設置為application/x-www-form-urlencoded然后使用FormUrlEncodedContent

var dict = new Dictionary<string, string>();
dict.Add("grant_type", "client_credentials");
dict.Add("scope", "read write");
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"https://login.sandbox.payoneer.com/api/v2/oauth2/token") { Content = new FormUrlEncodedContent(dict) };
var response = await client.SendAsync(request).ConfigureAwait(false);
var responseText = await response.Content.ReadAsStringAsync();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM