Search code examples
c#httpflurl

With flurl how can I pass multiple URL encoded form values with the same key?


I would like to replicate the following curl request where I pass in multiple form parameters with the same key, but using flurl in C#.

curl -X POST \
  https://example.com \
  --data "itemDescriptions=item 1" \
  --data "itemDescriptions=item 2"

The following is not possible due to the restriction that an anonymous object cannot have the same key twice:

"https://example.com".PostUrlEncodedAsync(new {
    itemDescriptions = "item 1",
    itemDescriptions = "item 2"
});

I have tried the following supposed workaround from this Flurl issue but it doesn't work even without the [] at the name of the parameter, but also my server doesn't accept them with that syntax:

var formValues = new List<KeyValuePair<string,string>>() 
{
    new KeyValuePair<string, string>("itemDescriptions", "item 1"),
    new KeyValuePair<string, string>("itemDescriptions", "item 2")
};
"https://example.com".PostUrlEncodedAsync(formValues);

With this I only end up with the last one in the list being sent in the request instead of both...


Solution

  • Changing the type of the form values to List<KeyValuePair<string, List<string>>> appears to generate the correct request:

    var formValues = new List<KeyValuePair<string,List<string>>>()
    {
        new KeyValuePair<string, List<string>>("itemDescriptions", new List<string> {"item 1", "item 2"}),
    };
    
    "https://example.com".PostUrlEncodedAsync(formValues);
    

    Both values appear in the request now.