Jeb50 Jeb50 -3 years ago 122
C# Question

Multiple GET no good w/ Attribute Routing?

This is supposed right:

/api/MyDataController.cs

public class MyDataController: ApiController
{
[HttpGet]
[Route("GetOne")]
public IHttpActionResult GetOne() { } // works w/o GetTwo

[HttpGet]
[Route("GetTwo")]
public IHttpActionResult GetTwo() { }
}


.js

$http({method: 'GET', url: '/api/MyData/GetOne'})... //works w/o GetTwo
$http({method: 'GET', url: '/api/MyData/GetTwo'})...


Same as this post, API version is

<package id="Microsoft.AspNet.WebApi" version="5.2.3"
targetFramework="net461" />


Both call to One and Two complained about GetOne,


"Multiple actions were found that match the request: GetOne on type
MyWeb.API.MyDataControllerGetOne on type
MyWeb.API.MyDataController"


It works if rem-out GetTwo() from Api controller.

Answer Source

This looks like the application is still using convention-based routing.

The reason for the clash is because the default convention-based route template api/{controller}/{id}does not usually provide an action parameter like this api/{controller}/{action}/{id}. If you want to get post actions to work via convention-routing when use the template provided before.

If you want to use attribute routing instead then you need to enable attribute routing in the WebApiConfig.cs file in order to allow the Rout Atrribute to work.

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

You would also need to update your routes to get what you want

[RoutePrefix("MyData")]
public class MyDataController: ApiController {

    //GET MyData/GetOne
    [HttpGet]
    [Route("GetOne")]  
    public IHttpActionResult GetOne() { } 

    //GET MyData/GetTwo
    [HttpGet]
    [Route("GetTwo")]
    public IHttpActionResult GetTwo() { }
}

Readup on attribute routing here Attribute Routing in ASP.NET Web API 2

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download