问题
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?
回答1:
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:
- 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 }
}
}
and define routing as
routes.MapRoute(
name: "route",
template: "{controller=Items}/{action=Get}/{id?}");
来源:https://stackoverflow.com/questions/45550507/route-to-different-actions-with-the-same-url-with-different-params