C # HttpClient Post String Array with different parameters

I am writing a C # api client and for most of the post requests I used FormUrlEncodedContent to post data.

List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();

keyValues.Add(new KeyValuePair<string, string>("email", email));
keyValues.Add(new KeyValuePair<string, string>("password", password));

var content = new FormUrlEncodedContent(keyValues);


But now I need to place the string array as one parameter. Something like below.

string[] arr2 = { "dir1", "dir2"};


How can I send this array along with other string parameters using C # HttpClient.


source to share

1 answer

I faced the same problem when I had to add both regular String parameters and a string array to the body of the Http POST request.

To do this, you need to do something similar to the example below (Assuming the array you want to add is an array of named strings dirArray


//Create List of KeyValuePairs
List<KeyValuePair<string, string>> bodyProperties = new List<KeyValuePair<string, string>>();

//Add 'single' parameters
bodyPropertiesAdd(new KeyValuePair<string, string>("email", email));
bodyProperties.Add(new KeyValuePair<string, string>("password", password));

//Loop over String array and add all instances to our bodyPoperties
foreach (var dir in dirArray)
    bodyProperties.Add(new KeyValuePair<string, string>("dirs[]", dir));

//convert your bodyProperties to an object of FormUrlEncodedContent
var dataContent = new FormUrlEncodedContent(bodyProperties.ToArray());




All Articles