Multiple GET verb on single route with different parameter name Web Api

我怕爱的太早我们不能终老 提交于 2020-01-06 08:04:28

问题


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."
}

回答1:


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.



来源:https://stackoverflow.com/questions/19296374/multiple-get-verb-on-single-route-with-different-parameter-name-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!