0

I'm trying to make an API call to third party URL, which is working fine through postman, but same request through C# HttpClient not working.

This is how I'm sending request in postman

enter image description here

C# Sample Code

 var nvc = new List<KeyValuePair<string, string>>();
 nvc.Add(new KeyValuePair<string, string>("PARAM1", "PARAM1 Value"));
 nvc.Add(new KeyValuePair<string, string>("PARAM2", "PARAM2 Value"));
 nvc.Add(new KeyValuePair<string, string>("PARAM3", "PARAM3 Value"));
  var req = new HttpRequestMessage(HttpMethod.Post, "Https://ThirdPartyURL") { 
                Content = new FormUrlEncodedContent(nvc) 
            };

Am I doing anything wrong here?

UPDATE #1: **

Fiddler Traces for postman request(which is working fine)

enter image description here

Fiddler Traces for C# Request(which is failing) enter image description here

Thanks in advance!

Regards, Moksh

Mox Shah
  • 2,967
  • 2
  • 26
  • 42
  • I see you're using `FormUrlEncodedContent` and in Postman is selected `form-data`. `FormUrlEncodedContent` sends `Content-Type: application/x-www-form-urlencoded; ` and form-data I believe should be `Content-Type: multipart/form-data; boundary=` – dcg Dec 04 '20 at 18:47
  • @dcg looks like that's the real issue, I just verified fiddler traces for both postman and C# and found same thing, Do you have sample code like how can we set content-type here ? – Mox Shah Dec 04 '20 at 18:50
  • I was just taking a look at [this](https://stackoverflow.com/a/3275002/4152153) answer, I think it may help you. – dcg Dec 04 '20 at 18:51
  • Also, take a look at [this](https://stackoverflow.com/a/53190314/4152153). There's `MultipartFormDataContent` class. – dcg Dec 04 '20 at 18:56
  • @dcg well, Earlier I tried `MultipartFormDataContent` but that was throwing 400 bad request. – Mox Shah Dec 04 '20 at 18:59
  • @dcg No luck with other link as well, same 400 bad request – Mox Shah Dec 04 '20 at 19:10
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/225542/discussion-between-mox-shah-and-dcg). – Mox Shah Dec 04 '20 at 19:16

1 Answers1

0

Instead of

var nvc = new List<KeyValuePair<string, string>>();

try to create a new class:

public class RecipientSender
{
public string Recipient_First_Name {get; set;}
public string Recipient_Last_Name {get; set;}
.....
}

and create httpclientrequest like this:

....
....

var recipientSender=new RecipientSender { Recipient_FirstName=..., }
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
httpClient.DefaultRequestHeaders.Accept.Add(contentType);
var stringData = JsonConvert.SerializeObject(recipientSender);
contentData = new StringContent(stringData, Encoding.UTF8, "application/json");
var httpResponseMessage=client.PostAsync(url, contentData);
.....

Serge
  • 40,935
  • 4
  • 18
  • 45