Mandar Jogalekar
Mandar Jogalekar

Reputation: 3281

Multiple controllers match the URL WebAPI

I have two web api methods with following route url's

[HTTPGET]
[Route("{Code}/{Id}")]

[HTTPGET]
[Route("{Code}/counter")]

Request /01/counter

{Id} is also a string parameter. Hence I am now getting error when calling Second api. "Multiple controllers action found for this Url" as webapi considers /01/counter valid for both routes.

I have seen few solutions with regex but can't find a working one yet. What is the good solution for this so that both Url's work as expected.

UPDATE:

I Found that the issue was occuring as the two methods were in different controllers hence webapi was having a problem in deciding which controller to choose. Once I moved them in the same controller, the problem is solved since , the route arguments are checked after controller is fixed.

Upvotes: 1

Views: 478

Answers (2)

habib
habib

Reputation: 2446

There is no problem in your snippet code.

[HTTPGET]
[Route("{Code}/{Id}")]

[HTTPGET]
[Route("{Code}/counter")]

It seems that in your Web API routing configuration action is not specifying like this. It's by default setting provided by the template.

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

In WebApi.config file use this code

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

Hopefully it will solve your problem.

Upvotes: 0

peflorencio
peflorencio

Reputation: 2472

If you are using WebAPI 2, you can use the RouteOrder property to define precedence when multiple actions match.

https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-order

 [HttpGet]
 [Route("{Code}/{Id}", RouteOrder = 2)]

 [HttpGet]
 [Route("{Code}/counter", RouteOrder = 1)]

If you are using MVC, you can use Order property:

https://learn.microsoft.com/en-us/previous-versions/aspnet/mt150670(v=vs.118)

[HttpGet]
[Route("{Code}/{Id}", Order = 2)]

[HttpGet]
[Route("{Code}/counter", Order = 1)]

Upvotes: 0

Related Questions