C# HttpClient Post String Array with Other Parameters
Asked Answered
F

1

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.

Fibster answered 22/4, 2015 at 8:13 Comment(5)
Why do you use a List<KeyValuePair<string, string>> instead of a Dictionary<string, string>?Posture
@Ksv3n I have to post a string array, not a string value.Fibster
Is using JSON a possibility?Lazos
Will keyValues.Add(new KeyValuePair<string, string>("directories", arr2.ToString() )); will work?Fibster
If you use JSON, you can simply serialize any data structure into a string represented in a JSON format.Lazos
E
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());
Enter answered 11/12, 2015 at 9:15 Comment(1)
I did this using ExpandoObject and serialized into a json.Fibster

© 2022 - 2024 — McMap. All rights reserved.