我认为你甚至不能编译你的代码ASP.NET Core Mvc 2.0
因为您有 2 个操作映射到同一路线[HttGet] api/values
:
AmbiguousActionException: Multiple actions matched.
记住,ASP.NET Web API
使用 HTTP 动词作为请求的一部分来确定要调用哪个操作。尽管它使用传统路由(您将操作命名为 Get、Post、Put 和 Delete 等),但如果您没有指定路由属性,我强烈建议您始终使用路由属性来注释您的控制器和操作。
API设计时间
现在由您作为开发人员来设计路线。请记住该路线应该是Uri
可以识别一个/多个资源。
-
使用名称作为路线的标识符
[Route("api/[controller]")]
public class CustomersController : Controller
{
// api/customers
[HttpGet]
public IActionResult Get()
{
...
}
// api/customers/dave
[HttpGet("{name:alpha}")] // constraint as a string
public IActionResult GetByName(string name)
{
...
}
}
-
使用名称作为过滤器,针对资源集合
[Route("api/[controller]")]
public class CustomersController : Controller
{
// api/customers
// api/customers?name=dave
[HttpGet]
public IActionResult Get(string name)
{
...
}
}
让你更加迷惑
api/customers/dave
仍会执行GetById
first!
[Route("api/[controller]")]
public class CustomersController : Controller
{
[HttpGet]
public IActionResult Get()
{
...
}
[HttpGet("{name}")]
public IActionResult GetByName(string name)
{
...
}
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
...
}
}
两种方法GetByName
and GetById
是潜在的候选人,但 MVC 选择GetById
方法优先,因为 MVC 会比较方法/模板名称{name}
and {id}
通过不区分大小写的字符串比较,以及i
出现在之前n
.
这时候你想把限制条件.
[Route("api/[controller]")]
public class CustomersController : Controller
{
[HttpGet]
public IActionResult Get()
{
...
}
// api/customers/dave
[HttpGet("{name:alpha}")]
public IActionResult GetByName(string name)
{
...
}
// api/customers/3
[HttpGet("{id:int}")]
public IActionResult GetById(int id)
{
...
}
}
您还可以指定Ordering too!
[Route("api/[controller]")]
public class CustomersController : Controller
{
[HttpGet]
public IActionResult Get()
{
...
}
// api/customers/portland
[HttpGet("{city:alpha}", Order = 2)]
public IActionResult GetByCity(string city)
{
...
}
// api/customers/dave
[HttpGet("{name:alpha}", Order = 1)]
public IActionResult GetByName(string name)
{
...
}
// api/customers/3
[HttpGet("{id:int}")]
public IActionResult GetById(int id)
{
...
}
}
如果没有Order
, 方法GetByCity
会比GetByName
因为字符 c 的{city}
出现在字符 n 之前{name}
。但如果您指定顺序,MVC 将根据Order
.
唉,帖子太长了……