问题描述
我正在使用以下路线构建api:/items
和/items/{id}
.现在,我想将此路由路由到两个不同的动作.我无法使用属性进行配置,这是config:
I'm building api with such routes:/items
and /items/{id}
.For now I want to route this routes to two different actions. I am not able to configure it with attributes, here is config:
routes.MapRoute(
"route1",
"/items",
new { controller = "Items", action = "Get" });
routes.MapRoute(
"route2",
"/items/{id}",
new { controller = "Items", action = "Get" });
但是这条路线是行不通的.我在哪里错了?
But this route just doesn't work. Where am I wrong?
推荐答案
除非有两个动作方法被映射到不同的HTTP方法,否则不可能有两个具有相同名称的动作方法并使用路由模板进行映射.模型绑定有效):
It's not possible to have 2 action methods with the same name and map them using route templating unless those methods are mapped to different HTTP method (all this due to how model binding is working):
public class ProductsController : Controller
{
public IActionResult Edit(int id) { ... }
[HttpPost]
public IActionResult Edit(int id, Product product) { ... }
}
但是可以,这可以使用属性路由来完成.如果您不能使用这种方法,则只有以下选项:
But yes, this is possible to do using attribute routing. If you cannot use this approach, then you have only the following options:
- 重命名动作名称之一;
- 使用可选的
id
参数将这两个动作组合为一个动作.
- rename one of the action's name;
- combine both actions into one with optional
id
parameter.
public class ItemsController : Controller
{
public IActionResult Get(int? id)
{
if (id.HasValue())
{ // logic as in second action }
else
{ // first action logic }
}
}
并将路由定义为
routes.MapRoute(
name: "route",
template: "{controller=Items}/{action=Get}/{id?}");
这篇关于使用不同的参数使用相同的网址路由到不同的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!