Writing FormUrlEncoded data with ASP.NET Web APIs
The code for this post can be downloaded in the MSDN Code Gallery.
The FormUrlEncodedMediaTypeFormatter class shipped with the ASP.NET Web APIs beta is one of the default formatters in the Web APIs and can be used to support incoming data from the application/x-www-form-urlencoded media type. This is the default format used for HTML form submission, and it has always been supported in ASP.NET MVC (but not in WCF, which was a constant feature request). This is also the default format used by jQuery when submitting objects, which makes supporting this format even more important, given the almost ubiquity of that library.
So ASP.NET Web APIs continues with the tradition of ASP.NET MVC and provides a formatter which supports consuming forms data natively. It also supports the complex objects format which is used by jQuery, in which the objects are “flattened” and all values are sent as key-value pairs as forms data. For example, this JavaScript object
- var data = {
- name: 'John',
- age: 33,
- luckyNumbers: [3, 7],
- children: [
- { name: 'Jack', age: 6 },
- { name: 'Jane', age: 4 }
- ]
- };
when sent as the body of a POST request (or other requests with a body) is encoded as follows (line breaks added for clarity)
name=John&age=33&luckyNumbers[]=3&luckyNumbers[]=7&
children[0][name]=Jack&children[0][age]=6&
children[1][name]=Jane&children[1][age]=4
The FormUrlEncodedMediaTypeFormatter, however, can only read form-urlencoded data; it cannot produce them, because the main scenario for which this formatter was created was to consume such data. There was one request for writing data on this format (for an API which needs to invoke an existing service which doesn’t support JSON input, and supports only forms data instead), so this post will show a simple media type formatter which can both read and write forms encoded data.
A small warning before going on: I haven’t been able to find any formal specification for the format used by jQuery when encoding complex types, so this is what I was able to find out from passing many different object types and observing what their wire representation was. In other words, it works on my machine. If you know of any formal specification of that format, please let me know.
The existing form encoded formatter already does all the reading part, so we can inherit from the type and only override the writing methods. Below is the virtual methods of the class, nothing new here – we only support JsonObject (which provides a good abstraction for JavaScript complex types), but supporting other types (such as JSON.NET’s JObject) should be trivial. When writing the type, start a new factory which first flattens the object in a list of key/value pairs, then writes them to the stream separated by ‘&’.
- class ReadWriteFormUrlEncodedMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter
- {
- private readonly static Encoding encoding = new UTF8Encoding(false);
- protected override bool CanWriteType(Type type)
- {
- return base.CanWriteType(type) || type == typeof(JsonObject);
- }
- protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
- {
- if (type == typeof(JsonObject))
- {
- return Task.Factory.StartNew(() =>
- {
- List<string> pairs = new List<string>();
- Flatten(pairs, value as JsonObject);
- byte[] bytes = encoding.GetBytes(string.Join("&", pairs));
- stream.Write(bytes, 0, bytes.Length);
- });
- }
- else
- {
- return base.OnWriteToStreamAsync(type, value, stream, contentHeaders, formatterContext, transportContext);
- }
- }
- }
Flattening the object means that for each of the object’s keys, we’ll push them to a stack and start flattening their values. At the end of the operation, the stack should be empty (otherwise some error happened), so we check that for debugging sake.
- private void Flatten(List<string> pairs, JsonObject input)
- {
- List<object> stack = new List<object>();
- foreach (var key in input.Keys)
- {
- stack.Add(key);
- Flatten(pairs, input[key], stack);
- stack.RemoveAt(stack.Count - 1);
- if (stack.Count != 0)
- {
- throw new InvalidOperationException("Something went wrong");
- }
- }
- }
The main logic of this formatter happens in the recursive Flatten method. Here we check all the possible types of objects which can be written out. jQuery doesn’t write out any null values, so we’re doing the same here. For arrays and objects, the method pushes the key into the stack and calls itself recursively for the value. Finally, for “primitive” values (numbers, strings, Boolean), we create the key by traversing the stack, separating them with square brackets. One thing which I noticed is that for arrays, the last element doesn’t have the index in the serialized format, as shown in the “luckyNumbers” member in the example above, so this code also accounts for that.
- private static void Flatten(List<string> pairs, JsonValue input, List<object> indices)
- {
- if (input == null)
- {
- return; // null values aren't serialized
- }
- switch (input.JsonType)
- {
- case JsonType.Array:
- for (int i = 0; i < input.Count; i++)
- {
- indices.Add(i);
- Flatten(pairs, input[i], indices);
- indices.RemoveAt(indices.Count - 1);
- }
- break;
- case JsonType.Object:
- foreach (var kvp in input)
- {
- indices.Add(kvp.Key);
- Flatten(pairs, kvp.Value, indices);
- indices.RemoveAt(indices.Count - 1);
- }
- break;
- default:
- string value = input.ReadAs<string>();
- StringBuilder name = new StringBuilder();
- for (int i = 0; i < indices.Count; i++)
- {
- var index = indices[i];
- if (i > 0)
- {
- name.Append('[');
- }
- if (i < indices.Count - 1 || index is string)
- {
- // last array index not shown
- name.Append(index);
- }
- if (i > 0)
- {
- name.Append(']');
- }
- }
- pairs.Add(string.Format("{0}={1}", Uri.EscapeDataString(name.ToString()), Uri.EscapeDataString(value)));
- break;
- }
- }
That’s it. In the project from code gallery I’ll include a test project which shows some examples of the conversions this formatter can do.