Search code examples
c#asp.net-web-api2asp.net-web-api-routingasp.net-mvc-5.2

Multiple actions were found that match the request when using actions in Route config


I'm currently building an API using Web API 2.2

I have the RESTful part of it working but now I need one non-RESTful controller:

 public class PremisesController : ApiController
    {
        private PremiseService _service;

        public PremisesController()
        {
            _service = new PremiseService();
        }

        [HttpGet]
        public IHttpActionResult Premise(string id)
        {
            id = id.Replace(" ", String.Empty).ToUpper();

            List<Premise> premises = _service.GetPremisesForPostcode(id);
            return Ok(premises);
        }

        [HttpGet]
        public IHttpActionResult Building(string id)
        {
            double premise = Convert.ToDouble(id);
            Building building = _service.GetBuildingsForPremise(premise);
            return Ok(building);
        }
    }

The routing config is as follows:

        config.MapHttpAttributeRoutes();

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

Im getting the error that it can't distinguish between the two methods when I initiate a GET action:

Multiple actions were found that match the request

So my question is Do I need to specify the Route attribute on top of each method and if yes, why? Doesn't the second route (ActionApi) deals with that situation?


Solution

  • EDIT:

    I just tested you're code and it works the way it is... maybe just it is unclear.

    • /api/Premises/Premise/8 --> will take you to your first action
    • /api/Premises/Building/8 --> will take you to your second action
    • /api/Premises/8 --> will cause error because the routing will go to the first rule api/{controller}/{id} with a GET request, then he can't distinguish which of the actions you want because they both match the first route: (api/Premises/{id})