11

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.

5
  • 1
    Why do you use a List<KeyValuePair<string, string>> instead of a Dictionary<string, string>? Commented Apr 22, 2015 at 8:15
  • @Ksv3n I have to post a string array, not a string value. Commented Apr 22, 2015 at 8:19
  • Is using JSON a possibility? Commented Apr 22, 2015 at 8:21
  • Will keyValues.Add(new KeyValuePair<string, string>("directories", arr2.ToString() )); will work? Commented Apr 22, 2015 at 8:28
  • If you use JSON, you can simply serialize any data structure into a string represented in a JSON format. Commented Apr 22, 2015 at 8:37

1 Answer 1

20

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());
Sign up to request clarification or add additional context in comments.

1 Comment

I did this using ExpandoObject and serialized into a json.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.