[SOLVED] curl works however PostAsync returns 500 internal server error

Issue

I am trying to convert the following code to c#.net

curl -X 'POST' \
  'https://someapi.io/api/function1' \
  -H 'accept: application/json' \
  -H 'X-API-Key: key' \
  -H 'Content-Type: application/json' \
  -d '{
  "abi": [{"inputs":[]}],
  "params": { "userAddress": "address" }
}'

however I am getting a 500 internal server error whereas the above code works fine.

var obj = new { abi = "[{\"inputs\":[]}]", @params = new { userAddress = "address" } };
var payload = JsonContent.Create(json);
// StringContent payload = new StringContent(JsonSerializer.Serialize(json), Encoding.UTF8, "application/json");

_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Add("X-API-Key", "key");
using (HttpResponseMessage response = await _client.PostAsJsonAsync($"{baseUri}?{signature}", payload).ConfigureAwait(false))
{
   if (response.IsSuccessStatusCode)
   {
       return await response.Content.ReadAsStringAsync();
   }
}

Any ideas what might be wrong?

Solution

abi needs to be passed as an array but you are passing it as a string:

var obj = new { abi = new[] 
{ 
   new {
        inputs = new string[0] //replace string with the array type you want
       }
},
 @params = new { userAddress = "address" } };


_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Add("X-API-Key", "key");
using (HttpResponseMessage response = await _client.PostAsJsonAsync($"{baseUri}?{signature}", obj).ConfigureAwait(false)) //pass obj here
{
   if (response.IsSuccessStatusCode)
   {
       return await response.Content.ReadAsStringAsync();
   }
}

Answered By – Aman B

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *