Api controller declaring more than one Get statement

后端 未结 2 924
失恋的感觉
失恋的感觉 2020-12-04 14:29

Using the new Api Controller in MVC4, and I\'ve found a problem. If I have the following methods:

public IEnumberable GetAll()

相关标签:
2条回答
  • 2020-12-04 14:53

    This is all in the routing. The default Web API route looks like this:

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

    With the default routing template, Web API uses the HTTP method to select the action. In result it will map a GET request with no parameters to first GetAll it can find. To work around this you need to define a route where the action name is included:

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

    After that you can star making requests with following URL's:

    • api/yourapicontroller/GetClients
    • api/yourapicontroller/GetStaffMembers

    This way you can have multiple GetAll in Controller.

    One more important thing here is that with this style of routing, you must use attributes to specify the allowed HTTP methods (like [HttpGet]).

    There is also an option of mixing the default Web API verb based routing with traditional approach, it is very well described here:

    • Web API: Mixing Traditional & Verb-Based Routing
    0 讨论(0)
  • 2020-12-04 14:55

    In case someone else faces this problem. Here's how I solved this. Use the [Route] attribute on your controller to route to a specific url.

    [Route("api/getClient")]
    public ClientViewModel GetClient(int id)
    
    [Route("api/getAllClients")]
    public IEnumerable<ClientViewModel> GetClients()
    
    0 讨论(0)
提交回复
热议问题