Multiple GET no good w/ Attribute Routing?

眉间皱痕 提交于 2019-12-11 06:48:34

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/42103266/multiple-get-no-good-w-attribute-routing

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