Question

How can possible to call different-different action on basis of parameter name using single route.

I need following

/api/v1/user
GET
key=dfddg&secret=fafassaf&query=select id from user where user like '%ggg%'

and

/api/v1/user
GET
key=dfddg&secret=fafassaf&ids=fadfdafdsf,faffasfasfsf,asfasfasfasfas,asfasfasfasf

I have written following code

[RoutePrefix("api/v1/user")]
public class UserController : ApiController
{
    [GET("")]
    public String GetAllUsers(String key, String secret, String query)
    {
        return "GetAllUsers";
    }

    [GET("")]
    public String GetLookupUserIds(String key, String secret, String ids)
    {
        return "GetLookupUserIds";
    }

but first case working fine but second one throwing exception

{
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost:14823/api/v1/user?key=rhdgsdgdsr&secret=fhdgdgdfhdfh&ids=fdfdf,dfadfff'.",
    "MessageDetail": "No action was found on the controller 'User' that matches the request."
}
Was it helpful?

Solution

I believe the issue here is that a request for api/v1/user is matched by the 1st route in the route table.(Note: route matching happens first where it doesn't consider query parameters and then action matching happens) Now, the 1st route in the route table could be reflection order based on which attribute routing is adding the actions to it. (you can check how the route table GlobalConfiguration.Configuration.Routes entries look like).

Attribute routing adds routes by assigning action variable the value of the action name. Web API's action selection has logic where if it sees that the action variable is assigned, it will try to look for the best matching action among list of actions with this same name (action overloading scenario like yours).

You can try the following:

  1. Have same action name for both methods above by using ActionName attribute.

  2. if 1. doesn't make sense, you could probably have different route temmplate for the actions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top