Home > Net >  Creating Postman request in C#
Creating Postman request in C#

Time:12-28

I am able to make the following request in Postman but not able to in C#. I'm guessing it's due to the json but tried a few different ways and still nothing.

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'

My Code returns text "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;

CodePudding user response:

If you need to set the content as application/x-www-form-urlencoded then use 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();

CodePudding user response:

If you are serializing the request body to JSON, then you need to set the Content-Type as application/json

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