Web API Body Params
I was just working on an API route that ought allow updating several different records using the same (mostly, and they can be null if not necessary) params for each record. It's essential that the route handle updating a variable number of records at once--from 1 to... infinity and beyond! I was trying to figure out how to structure the JSON params for such a route.
At first I thought it would be cool to have top-level keys (record ID) pointing to the params for that particular record--nested objects, like so:
{ "id1": { "key1":"value1", "key2":"value2" }, "id2": { "key1":"value1", "key2":"value2" } }
I investigated how to accomplish this with Web API, using the [FromBody] param parsing. I tried to make a class that would have a Dictionary property, but this dead-ended quickly. Some slight googling yielded the JObject class. This was cool, in that now I was able to pass in an arbitrary JSON object to my API route. But now I had to write parsing logic to extract the proper data structures out of this JObject, and this wasn't so straightforward. It's certainly doable:
foreach (KeyValuePair<string, JToken> data in _params) { // do stuff with data.Key; // do stuff with data.Value; }
But then I'd need to manually instantiate the individual params objects, and this is far less fun than having Web API do it all automagically.
So I re-thought my approach! "Wait a second," I thought. "Couldn't the id attribute be just another key/value pair in each object? And isn't an array of objects a perfectly valid JSON object?" It sure can, and it sure is! So I restructured my JSON params to look like this:
[ { "id":"id1", "key1":"value1", "key2":"value2" }, { "id":"id2", "key1":"value1", "key2":"value2" } ]
Now in my API route I am able to specify all the properties of one of the objects on a RecordModificationParams class, and have Web API automagically parse a list of any length using [FromBody]List<RecordModificationParams> in the controller function signature. Win!















