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?

Related Articles:

    About Keith Dahlby

    I'm a .NET developer, Git enthusiast and language geek from Cedar Rapids, IA. I work as a software guru at J&P Cycles and studied Human-Computer Interaction at Iowa State University.
    This entry was posted in ASP.NET Web API and tagged , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post.
    • Michael Chandler

      Why don’t you like ‘ids’?

    • Abhaygautam777

      very informative post indeed.. being enrolled in http://www.wiziq.com/course/57-fresher-training-projects was looking for such articles online to assist me.. and your post helped me a lot 

    • http://nissimfinch.weebly.com/ MartinEvans

      hi, how to pass the parameter in different data type with same name of variable  ?is it possible ?