Search code examples
c#asp.net-web-apiparametersasp.net-web-api-routing

Web API Multiple actions were found with GetAll() and GetByIds(int[] ids)


Using the standard route:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

With these actions:

public class ValuesController : ApiController
{
    // GET api/values
    public string GetAll()
    {
        return "all";
    }

    // GET api/values/5
    public string GetById(int id)
    {
        return "single";
    }

    // GET api/values?ids=1&ids=2
    public string GetByIds([FromUri] int[] ids)
    {
        return "multiple";
    }

And make a request to /api/values, I get this exception:

Multiple actions were found that match the request: 
System.String GetAll() on type MvcApplication4.Controllers.ValuesController
System.String GetByIds(Int32[]) on type MvcApplication4.Controllers.ValuesController

I've been spinning my wheels trying to find a solution around this. It's my belief that the GetAll and GetByIds actions are considered Multiple here, but they aren't because the GetByIds has a different signature.

Is there a work around for this that doesn't involve adding {action} to the route?


Solution

  • The only way I found to do this is to combine the GetAll and GetByIds action and switch case the length of ids.

    public class ValuesController : ApiController
    {
        // GET api/values/5
        public string GetById(int id)
        {
            return "single";
        }
    
        // GET api/values
        // GET api/values?ids=1&ids=2
        public string GetByIds([FromUri] int[] ids)
        {
            switch (ids.Length)
            {
                case 0:
                    return "all";
    
                default:
                    return "multiple";
            }
        }