Asp.net mvc “不显示”;索引“;在URL中,并为MVC5路由提供参数

Asp.net mvc “不显示”;索引“;在URL中,并为MVC5路由提供参数,asp.net-mvc,asp.net-mvc-routing,Asp.net Mvc,Asp.net Mvc Routing,我正在尝试在我的一个MVC区域设置一些路由 我有一个名为AgentGroups的控制器。我正在努力实现以下目标: 从URL中删除索引 为索引操作提供一个参数 允许所有其他操作的名称出现在URL中,并为其提供可选参数 例如,我希望下面的工作 /s/agentgroups < (Index action) /s/agentgroups/1 < (Index action) /s/agentgroups/someotheraction /s/agentgroups/someothe

我正在尝试在我的一个MVC区域设置一些路由

我有一个名为
AgentGroups
的控制器。我正在努力实现以下目标:

  • 从URL中删除
    索引
  • 为索引操作提供一个参数
  • 允许所有其他操作的名称出现在URL中,并为其提供可选参数
例如,我希望下面的工作

/s/agentgroups   < (Index action)
/s/agentgroups/1 < (Index action)
/s/agentgroups/someotheraction
/s/agentgroups/someotheraction/1
这适用于我给出的4个URL示例中的3个,不正确的示例是:

/s/agentgroups/1 < (Index action)
/s/agentgroups/1<(索引操作)
我很确定它认为
1
参数是一个动作名称,因此它不起作用但是,如果,我像常规查询字符串一样传递参数,即:
?agentgroupid=1
,则它确实有效,但如果可能,我希望避免这种情况


如何更改路线以实现所需的行为?

您可以重新排列区域路线,因为供应商索引比供应商索引更具体(仅用于索引操作)。然后,需要为供应商索引中的agentgroupid参数添加约束

由于参数是可选的并且必须匹配整数,我们可以使用regex
\d*
,但是对于更复杂的模式,您可能需要创建自己的路由约束

因此,您的区域路由可能如下所示:(在您的情况下,名称空间将不同,甚至不需要):


agentgroupid
在您的路径“供应商索引”中是整数吗?@DanielJ.G。是的,
agentgroupid
在两个路由中都是整数。
/s/agentgroups/1 < (Index action)
context.MapRoute(
    "Suppliers_index",
    "s/agentgroups/{agentgroupid}",
    defaults: new { controller = "AgentGroups", action = "Index", agentgroupid = UrlParameter.Optional },
    constraints: new { agentgroupid = @"\d*" },
    namespaces: new[] { "WebApplication6.Areas.AgentGroups.Controllers" }
);

context.MapRoute(
    "Suppliers_actions",
    "s/{controller}/{action}/{agentgroupid}",
    defaults: new { controller = "AgentGroups", agentgroupid = UrlParameter.Optional },
    namespaces: new[] { "WebApplication6.Areas.AgentGroups.Controllers" }
);