FormUrlEncodedContent with support for array values

Posted by & filed under Dev', Tips.

As convenient as System.Web.Http is for .NET developers, while working on my current project, I discovered that it did not support array values out of the box.
When you want to post something in the ‘x-www-form-urlencoded’ form, and using the FormUrlEncodedContent class, you are limited to string keys and values as FormUrlEncodedContent is build out of an IEnumerable<KeyValuePair<string, string>> (or more commonly a Dictionary<string, string>) object.

What if I want to send an array like :
Accept: */*
Content-Length: 40
Accept-Encoding: identity
Connection: Keep-Alive
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
User-Agent: NativeHost
Pragma: no-cache

Well you can’t. Or you could rewrite and extend FormUrlEncodedContent.
Or you could just reuse the following gist, because that’s precisely what I’ve done :

Note that I only needed (thus added) support for array string values, it can be extended for array keys, array of numeric values, …

Comments are closed.