Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HttpClient Post String Array with Other Parameters

I am writing a C# api client and for most of the post requests I used FormUrlEncodedContent to post the 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 post a string array as one parameter. Some thing like below.

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

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

like image 513
Yasitha Avatar asked Apr 22 '15 08:04

Yasitha


1 Answers

I ran into the same issue where I had to add both some regular String parameters and a string array to a Http POST Request body.

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

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

//Add 'single' parameters
bodyProperties.Add(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());
like image 133
RWIL Avatar answered Sep 18 '22 12:09

RWIL