[英]Map two different routes to the same controller action
I am working on extending the example at: https://docs.asp.net/en/latest/tutorials/first-web-api.html 我正在以下位置扩展示例: https : //docs.asp.net/zh/latest/tutorials/first-web-api.html
They have a ToDo apis: /api/todo
and /api/todo/{id}
. 他们有一个ToDo api:
/api/todo
和/api/todo/{id}
。
I want to extend it to ToDoGroups /api/ToDoGroup
. 我想将其扩展到ToDoGroups
/api/ToDoGroup
。
Under ToDoGroup, I want to reach a ToDo by the follwoing: /api/ToDoGroup/{id}/ToDo/{id}
. 在ToDoGroup下,我想通过以下方式到达ToDo:
/api/ToDoGroup/{id}/ToDo/{id}
。
How can I make it point to the same controller action? 如何使其指向相同的控制器动作? For example the following action below will also have another route like
[HttpGet("ToDoGroup/{ToDoGroupid}/ToDo/{ToDoid}", Name = "GetTodo")]
例如,下面的操作还将具有另一个路由,例如
[HttpGet("ToDoGroup/{ToDoGroupid}/ToDo/{ToDoid}", Name = "GetTodo")]
[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(string id)
{
var item = TodoItems.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
first change the controller's route prefix: 首先更改控制器的路由前缀:
[Route("api/todogroup/{groupId:int}")]
public class TodoController : Controller
then change your action's route: 然后更改您的操作路线:
[HttpGet("todo/{id}", Name = "GetTodo")]
public IActionResult GetById(int groupId, string id)
edit: to get both routes, you can do this: 编辑:要获得两条路线,您可以执行以下操作:
[Route("api")]
public class TodoController : Controller
[HttpGet("todo/{id}", Name = "GetTodo")]//api/todo/43
public IActionResult GetById(string id)
[HttpGet("todogroup/{groupdId:int}/todo/{id}", Name = "GetGroupTodo")]//api/todogroup/100/todo/43
public IActionResult GetById(int groupId, string id)
Asp.Net Web Api has a way of negating a route prefix (the route specified on the controller), but I cant find an equivalent in Asp.Net Core. Asp.Net Web Api可以否定路由前缀(在控制器上指定的路由),但是我在Asp.Net Core中找不到等效项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.