I want to convert my javascript code to C#, I’m confused with the content-type of the header as application/json and the body as urlencoded, Please can anyone help me with converting this request to C#, thank you.
const echoPostRequest = {
url: 'https://'+ pm.environment.get('apigw') +'/token',
method: 'POST',
header: 'Content-Type:application/json',
header: 'Authorization: Basic '+ base64EncodedPassword,
body: {
mode: 'urlencoded',
urlencoded: [
{key: "grant_type", value: "client_credentials", disabled: false},
{key: "scope", value: "scope_test", disabled: false}
]
}
};
I tried this code below, is it correct ?
//This code is just for generating a base-64 code from a string
string basicToken = ClientID+ ":" +ClientSecret;
var basicBytes = System.Text.Encoding.UTF8.GetBytes(basicToken);
string basic = Convert.ToBase64String(basicBytes);
//this is the rest api call
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", basic);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, TokenUri);
var postData = new
{
grant_type= "client_credentials",
scope= "scope-test"
};
var content = new StringContent(JsonConvert.SerializeObject(postData), Encoding.UTF8, "application/x-www-form-urlencoded");
request.Content = content;
var response = await client.SendAsync(request);