WebApi Exception: Multiple Action were found that match the request.

Usually webapi controller contains GET,GET(id),Post,Put,Patch & Delete methods but sometimes we need to create multiple get or post method or more custom methods to support http verbs.

Let say we have existing Get() method and now we want to add one more custom method names as “GetALL()” to support http Get verb.My Api Controller code looks like:

c2

When you defined your new method with http Get verb along with existing Get() method  and run webapi than below error comes:

C1

WebApiConfig.cs for above code which is created by default when new api project created.

C3

So talk about why this error comes if every thing is perfect in code.So look at the defined route in config file and .In webapi routing only controller name is mentioned in route template and there is no action like (Get,Post or any Custom Action Name) are defined.

Here is the difference in mvc routing and Webapi routing. In mvc routing action name are by default included in Url’s while in webapi actions names are not mandatory.

MVC Route: url: “{controller}/{action}/{id}”

WebApi Route: routeTemplate: “api/{controller}/{id}”

So when ever any request comes to webapi,it always goes to default http verbs and if default GET or Post methods used then it returns a response to the client.

But when we have defined some custom methods along with default Api methods than same request will thrown an exception because now there are multiple action methods that supports http verbs  and server not able to identify which method have to execute.

Why this happened because we have not defined any specific action name in webapi Route.

So what is the solution of this problem as we need many custom action names along with default http verbs in our webapi solution to solve the day-to-day business needs.So question comes in mind whether custom method names are allowed in webapi or not.

Then answer is “yes”,off-course we can add custom action names as much as we want but some changes have to make in webapi routing to support custom action names.

To support custom action method names we have to add {action} with controller name in default route as per below:

routeTemplate: “api/{controller}/{action}/{id}”

Now Complete Webapiconfig.cs after make some changes:

c4

Now Test our methods with these changes.

.1.when request goes to default methods:

C5

2.When request goes to custom action method (GetAll)

C6