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

Web API routing with multiple parameters


I'm trying to work out how to do the routing for the following Web API controller:

public class MyController : ApiController
{
    // POST api/MyController/GetAllRows/userName/tableName
    [HttpPost]
    public List<MyRows> GetAllRows(string userName, string tableName)
    {
        ...
    }

    // POST api/MyController/GetRowsOfType/userName/tableName/rowType
    [HttpPost]
    public List<MyRows> GetRowsOfType(string userName, string tableName, string rowType)
    {
        ...
    }
}

At the moment, I'm using this routing for the URLs:

routes.MapHttpRoute("AllRows", "api/{controller}/{action}/{userName}/{tableName}",
                    new
                    {
                        userName= UrlParameter.Optional,
                        tableName = UrlParameter.Optional
                    });

routes.MapHttpRoute("RowsByType", "api/{controller}/{action}/{userName}/{tableName}/{rowType}",
                    new
                    {
                        userName= UrlParameter.Optional,
                        tableName = UrlParameter.Optional,
                        rowType= UrlParameter.Optional
                    });

but only the first method (with 2 parameters) is working at the moment. Am I on the right lines, or have I got the URL format or routing completely wrong? Routing seems like black magic to me...


Solution

  • The problem is your api/MyController/GetRowsOfType/userName/tableName/rowType URL will always match the first route so the second is never reached.

    Simple fix, register your RowsByType route first.