在MVC 4.0中实现动态操作的路由

时间:2014-09-10 12:13:31

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing actionmethod

是否可以在MVC中定义一个基于部分路由动态解决操作的路由?

public class PersonalController
{
  public ActionResult FriendGroup()
  {
      //code
  }

  public ActionResult RelativeGroup()
  {
      //code
  }

  public ActionResult GirlFriendGroup()
  {
      //code
  }
}

我想为下面的组操作方法实现路由

Url: www.ParlaGroups.com/FriendGroup
     www.ParlaGroups.com/RelativeGroup
     www.ParlaGroups.com/GirlFriendGroup

routes.MapRoute(
    "Friends",
    "/Personal/{Friend}Group",
    new { controller = "Personal", action = "{Friend}Group" }
);
routes.MapRoute(
    "Friends",
    "/Personal/{Relative}Group",
    new { controller = "Personal", action = "{Relative}Group" }
);
routes.MapRoute(
    "Friends",
    "/Personal/{GirlFriend}Group",
    new { controller = "Personal", action = "{GirlFriend}Group" }
);

我如何进行上述路由实施?

2 个答案:

答案 0 :(得分:4)

以下路由将允许MVC使用Url的第二部分来确定ActionResult:

routes.MapRoute(
"Friends",
"Personal/{action}",
new { controller = "Personal" }
);

以下网址将匹配:

www.ParlaGroups.com/Personal/FriendGroup 其中“FriendGroup”是ActionResult www.ParlaGroups.com/Personal/RelativeGroup 其中“RelativeGroup”是ActionResult www.ParlaGroups.com/Personal/GirlFriendGroup 其中“GirlFriendGroup”是ActionResult

答案 1 :(得分:0)

public class PersonalController
{
  public ActionResult FriendGroup()
  {
   //code
  }

  public ActionResult RelativeGroup()
  {
   //code
  }

  public ActionResult GirlFriendGroup()
  {
   //code
  }
}

 Url: www.ParlaGroups.com/FriendGroup
      www.ParlaGroups.com/RelativeGroup
      www.ParlaGroups.com/GirlFriendGroup


 routes.MapRoute(
  "Friends",
  "/{action}",
  new { controller = "Personal"}
 );