Multiple GET no good w/ Attribute Routing?

2019-07-28 05:59发布

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.

2条回答
劳资没心,怎么记你
2楼-- · 2019-07-28 06:32

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

查看更多
再贱就再见
3楼-- · 2019-07-28 06:34

This is additional answer for legacy app developers like me:

  • migrated a huge legacy .aspx WebForm app from VS 08 (.NET 2.x) to VS 15 (.NET 4.6)
  • revive by adding in new technology like API.

After digging around, this is the best found. If you just have Global.asax without .cs, simply add it into .asax.

查看更多
登录 后发表回答