MVC 5:控制器基于动作的路由

时间:2014-03-18 08:24:34

标签: asp.net-mvc asp.net-mvc-routing url-routing asp.net-mvc-5

有没有办法根据控制器的动作设置不同的路由?

例如:

默认路由

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

这会使网址看起来像

localhost:/Home/{someaction}/{id}

如果控制器操作是

public ActionResult SomeAction(int id)
{
   return Content("Sup?");
}

但是假设我有这个动作

public ActionResult AnotherAction(Guid productCategoryId, Guid productId)
{
   return content("Hello!");
}

如果我没有自定义路由,则路由看起来像

localhost:/Home/AnotherAction?productCategoryId=someGuidId&productId=someGuidId

但是对于此操作,如果我希望路线看起来像

localhost/Home/AnotherAction/productCategoryGuidId/productGuidId

我该怎么做?

我添加了自定义路线

    routes.MapRoute(
        name: "appointment",
        url: "{controller}/{action}/{appointmentId}/{attendeeId}",
        defaults: new {controller = "Home",action = "Index", appointmentId = "",attendeeId="" }
    );

但是如何说控制器使用该路线而不是默认路线的动作。

另外,我读到MVC 5中有attribute routing。这对我的情况有帮助吗?我将如何在我的案例中使用它?

1 个答案:

答案 0 :(得分:0)

在默认路由之前注册自定义MapRoute。首先在表格路线中计算其顺序。 路径按它们在RouteCollection中出现的顺序应用 宾语。 MapRoute方法将路径添加到集合的末尾,这意味着路径通常按照我们添加它们的顺序应用。

希望它会有所帮助