Search code examples
c#flurl

Flurl Array Encoding


I am attempting to post some data that includes a string array to an endpoint but receiving an error "Invalid array"

Doing this:

   .PostUrlEncodedAsync(new
     {
        amount = 1000,
        allowed_source_types = new[] { "card_present" },
        capture_method = "manual",
        currency = "usd"
     });

Results in this being posted:

amount=1000&allowed_source_types=card_present&capture_method=manual&currency=usd

The API vendor complains that the array that I posted is invalid. When I do this:

    .PostUrlEncodedAsync(
             "amount=1000&allowed_source_types[]=card_present&capture_method=manual&currency=usd"
    );

Results in this being posted:

amount=1000&allowed_source_types[]=card_present&capture_method=manual&currency=usd

The API vendor is happy and I get the expected results.

Question: Is this a bug and should the allowed_source_types parameter have included the [ ] as initially detailed here?


Solution

  • It's not a bug. As mentioned in the comments, there's no standard for URL-encoding a collection, but doing it like this:

    x[]=1,2,3
    

    is a lot less common than doing it like this:

    x=1&x=2&x=3
    

    The latter is how Flurl has implemented it.

    The trouble with doing it the way the API requires is that [] are not valid in a C# identifier, so the typical object notation won't work. But Flurl gives special treatment to Dictionary objects, so your best bet is to do it like this:

    .PostUrlEncodedAsync(new Dictionary<string, object>
    {
        ["amount"] = 1000,
        ["allowed_source_types[]"] = "card_present", // or string.Join(",", allowedSourceTypes)
        ["capture_method"] = "manual",
        ["currency"] = "usd"
     });