ASP.NET Web API List Parameter Binding
We chased our tails on this a bit today, so hopefully someone finds this useful.
The Problem
Your action needs to accept a list of primitives but your list parameter (of type T[]
, IEnumerable<T>
, List<T>
, etc) always comes back null
. You’re pretty sure an identical parameter has always work fine for an MVC action.
The Solution
Add [ModelBinder]
to the parameter:
public class ValuesController : ApiController { // GET api/values?id=Hello&id=%20world! public string Get([ModelBinder]List<string> id) { return string.Join(",", id); } }
Explanation
According to Mike Stall’s detailed post on Web API parameter binding, Web API only uses model binding for “simple types”, falling back on formatters for everything else. Adding [ModelBinder]
forces the complex types to use model binding anyway.
Related but not constructive: it feels weird naming a list parameter “id”, but even more weird using the API if it were named “ids”. Maybe just “x” instead?