Http Client correct way to pass content during post api call

Viewed 1278

Below is code snippet for POST api call where I am stuck with error:

Bad request

After searching the web, I understand that you get this error when you don't follow proper payload syntax or pass proper payload data while making a post api call.

Here are different ways that I tried so far but unfortunately none work.

// payload data's class represantation,
    public class DNCAddressInfo
        {
            [JsonProperty("dncAddress")]
            public string DNCAddress { get; set; }
            [JsonProperty("checkForPhoneRejection")]
            public bool CheckForPhoneRejection { get; set; }
            [JsonProperty("checkForPhoneFormats")]
            public bool CheckForPhoneFormats { get; set; }
        }

First try:

DNCAddressInfo dncObj = GetPayloadData();
string payload = JsonConvert.SerializeObject(dncObj);
var content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsJsonAsync(url, content).ConfigureAwait(false); // response: error code: 400 , bad request

Second try:

    DNCAddressInfo dncObj = GetPayloadData();
JObject jsonObject = new JObject
            {
                ["dncAddress"] = JsonConvert.SerializeObject(dncObj.DNCAddress),
                ["checkForPhoneRejection"] = JsonConvert.SerializeObject(dncObj.CheckForPhoneRejection),
                ["checkForPhoneFormats"] = JsonConvert.SerializeObject(dncObj.CheckForPhoneFormats)
            };

 var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
 HttpResponseMessage response = await _client.PostAsJsonAsync(url, content).ConfigureAwait(false);// response: error code: 400 , bad request

Third try:

string payload = "{\"dncAddress\": \"91#1231123\", \"checkForPhoneRejection\": false, \"checkForPhoneFormats\": false}"; // sample payload data taken from api providers document
var content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsJsonAsync(url, content).ConfigureAwait(false); // response: error code: 400 , bad request

All three approaches resulted in same error,

StatusCode: 400, ReasonPhrase: '400'

Request header is , 
Headers = {Authorization: Basic XXXXX;
Accept: application/json
X-Requested-With: rest
Cache-Control: no-cache
}

Response from Postman looks all fine. Here is snapshot of same.

Postman response

Is there anything I am doing wrong here or missing anything?

2 Answers

With PostJsonAsync method, you don't need to manually serialize an object to json, just pass it as it is:

DNCAddressInfo dncObj = GetPayloadData();
HttpResponseMessage response = await _client.PostAsJsonAsync(url, dncObj).ConfigureAwait(false);

or you can use newer HttpClient.PostAsync:

DNCAddressInfo dncObj = GetPayloadData();
string payload = JsonConvert.SerializeObject(dncObj);
var content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsync(url, content).ConfigureAwait(false);

References: HttpClient.PostAsync Method, HttpClientExtensions.PostAsJsonAsync Method

"PostAsJsonAsync" method serializes data inside. When you pass "StringContent" to this method then HttpClient serializes "StringContent" to Json and sends wrong data.

Try to use "PostAsync" instead of "PostAsJsonAsync".

Related