0

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);
  • You are missing the HTTP header Content-Type:application/json and the Content length (number of bytes). Java is probably automatically adding the byte count. With HTTP different application that create request to different things in the background and just because the code works with one tool doesn't mean it is automatically going to work with another tool. Often the default HTTP headers are different when you go from one tool to another. – jdweng Apr 15 '23 at 14:47
  • @jdweng Thanks for your reply, please can you specify how, because when I Add var request = new HttpRequestMessage(HttpMethod.Post, TokenUri); request.Headers.Add("Content-Type", "application/json"); it doesn't work. – Hamid Elouardaoui Apr 15 '23 at 15:13
  • the are a few samples of adding headers at following posting : https://stackoverflow.com/questions/29801195/adding-headers-when-using-httpclient-getasync – jdweng Apr 15 '23 at 17:05

1 Answers1

0

The Header it is by default set to Content-Type:application/json in C# HttpClient. This is the exact steps to send such request in C# :


    HttpClient client = new HttpClient();

    client.DefaultRequestHeaders.Add("Authorization", "Basic " + basic);
            var request = new HttpRequestMessage(HttpMethod.Post,tokenUrl);
            request.Headers.Add("Authorization", "Basic " + basic);
            var collection = new List<KeyValuePair<string, string>>();
            collection.Add(new("grant_type", "client_credentials"));
            collection.Add(new("scope", "scope_test"));
            var content = new FormUrlEncodedContent(collection);
            request.Content = content;
            var response = await client.SendAsync(request);