将两条路线结合到一个动作

combine two routes to one action

我想定义一个 MapRoute,它可以将两条不同的路线映射到一个动作。

我有一个创建地址的操作:

public class AddressesController : BaseController
{
    public ActionResult Create()
    {
        ...
    }
}

以下两条路线应映射到操作:

/Addresses/Create -> 创建新地址
/Projects/3/Addresses/Create -> 为项目创建一个新地址,id = 3

我尝试了以下 MapRoute 配置来完成此操作,但没有成功:

routes.MapRoute(
    name: "CreateAddress",
    url: "{projects}/{projectId}/{controller}/{action}",
    defaults: new { projects = "", projectId = UrlParameter.Optional, controller = "Addresses", action = "Create" },
    constraints: new { project = "(Projects)?" });

使用此配置,路由 /Projects/3/Addresses/Create 正常但 /Addresses/Create 无效。

您不能在同一条路线上同时使用两种方式。

您只需要指定额外的路由,因为 ASP.NET MVC 带有一个默认路由,它将确保 /Addresses/Create 可以工作:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

对于 /Projects/3/Addresses/Create 将其放在上述路线之前:

routes.MapRoute(
    name: "CreateAddress",
    url: "Projects/{projectId}/{controller}/{action}",
    defaults: new { controller = "Addresses", action = "Create" });