Home > Mobile >  WebApi differentiating Routing with Parameters
WebApi differentiating Routing with Parameters

Time:05-18

Apologies in advance if this was asked before but I can't find a direct answer that will help me fully understand routing.

Let's say we have the following scenario:

1. api/users             Routes to Get() //Retrieves all users
2. api/users/{user}      Routes to Get(string user) //api/users/IE1
3. api/users/?user=IE1   ????????? Get(string user = null, string emailAddress=null...)

I am trying to have both 2 and 3 running simultaneously. The reason I am trying to do this is because 3 can have multiple query parameters such as country, email addresses etc of a user.

Now 2 and 3 will clash with a "Multiple actions were found that match the request" when there is only 1 parameter.

Is there a way to fix this without creating another Route such as /api/users/searchbyUser/ as I am trying to keep it tidy on one Route - users?

CodePudding user response:

Actually 1 and 3 will clash, not 2 and 3 since you have only nullable parameters on the 3rd get. The Get (1) without any parameters will be the same as (3) all the nullables - there is no difference in signature.

You have multiple options to consider, but I would advise to have only one Get method: You have one method (no 3) when user = null and no other parameters have values you will return all users (1). If any of the parameters have values you can return the users based on the query values (like a combination of 2 and 3 if you like).

CodePudding user response:

Try your request with api/users/IE1?emailAddress=null, this will work in the 3rd routing.

  • Related