Search code examples
asp.netasp.net-web-apiasp.net-web-api2attributerouting

.net WebApi attribute routing with a collection parameter


I was so sure I'd done this before, but I cannot get this to work.

I have a web api 2 controller, and I want to have two methods.
One which takes a single ID and returns one object.
One which takes multiple ID's and returns a collection of objects.

So I have something similar to this:

[RoutePrefix("products/{company}/{dept}")]
public class ProductsController : ApiController
{
    [Route("{id:int}")]
    public async Task<IHttpActionResult> Get(string company, string dept, int id)
    {
         // this method works OK.
         ...
         return this.Ok(product);
    }

    [Route("")]
    public async Task<IHttpActionResult> Get(string company, string dept, IEnumerable<int> ids)
    {
        // ids is always null, so this method fails.
        ...
        return this.Ok(products);
    }
}

I can call the first method fine, with something like:

/products/foo/bar/1000

I expected to be able to call the second method with something like this, but although the method is hit, the ids collection is always null:

/products/foo/bar/?ids=1000&ids=1001&ids=1002

Am I missing something obvious?


Solution

  • You just need to add [FromUri] before parameter.

    [Route("")]
    public async Task<IHttpActionResult> Get(string company, string dept, [FromUri] IEnumerable<int> ids)
    {
        // ids now are filled with data ;)
        ...
        return this.Ok(products);
    }