Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient Post request with Json body

I am trying to send a POST request to a API with a JSON body and a param (param) in the URL.

The request goes through fine but the response sent back from API suggests that the values from customObj are not passed through to the API?

I have changed my implementation several times but can't seem to figure out as to why the body message couldn't be getting passed? I have checked the curl and can see it consists the body and JSON message.

Only thing I can think of is Content-Type: has application/json-patch+json whereas it should be only application/json

class customObj{
    public string param1 {get;set;}
    public string param2 {get;set;}
    public string param3 {get;set;}
}
string result;
var url = $"/test/{param}/dothis";

var jSonData = JsonConvert.SerializeObject(customObj);

using (var httpClient = new HttpClient())
{
    httpClient.BaseAddress = new Uri("https://www.testapi.com");

    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    using (var response =
        await httpClient.PostAsync(url, new StringContent(jSonData, Encoding.UTF8, "application/json")))
    {
        using (var content = response.Content)
        {
            var result = await content.ReadAsStringAsync();
        }
    }
}

CURL

curl -X POST "<url>" -H "accept: application/json" 
-H "Content-Type: application/json-patch+json" -d "{ \"param1\": \"test1\", \"param2\": \"test2\", \"param3\": \"test3\"}"
like image 452
KJSR Avatar asked Jan 27 '26 21:01

KJSR


1 Answers

Finally resolved this. The issue was due to me using PascalCasing inside my Json body and the end point using camelCasing so it was not able to read the property values.

So instead of this

var jSonData = JsonConvert.SerializeObject(customObj);

I had to use the camel casing resolver when I serilized my json object.

var changePassObj = JsonConvert.SerializeObject(customObj, 
                new JsonSerializerSettings 
                { 
                    ContractResolver = new CamelCasePropertyNamesContractResolver() 
                });
like image 84
KJSR Avatar answered Feb 03 '26 09:02

KJSR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!