Route to different actions with the same url with different params

落花浮王杯 提交于 2021-01-04 05:56:12

问题


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

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