我不知道此功能是否支持开箱即用,但您始终可以编写自定义路由来实现它:
public class MyRoute : Route
{
public MyRoute() :
base(
"{controller}/{action}/{parentid}/{currentid}",
new RouteValueDictionary(new
{
controller = "home",
action = "display",
currentid = UrlParameter.Optional
}),
new RouteValueDictionary(new
{
// adjust the constraint if your ids are not numeric
// but you must have a constraint when a route parameter is
// non optional unless this is the last parameter
parentid = @"^([0-9])+$"
}),
new MvcRouteHandler()
)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var rd = base.GetRouteData(httpContext);
if (rd == null)
{
return null;
}
var currentid = rd.Values["currentid"] as string;
if (!string.IsNullOrEmpty(currentid))
{
return rd;
}
rd.Values["currentid"] = rd.Values["parentid"];
return rd;
}
}
然后注册这条路线:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add("myroute", new MyRoute());
}
现在假设您已经定义了以下控制器:
public class HomeController : Controller
{
public ActionResult Display(int parentid, int currentid)
{
return Content(string.Format("{0}, {1}", parentid, currentid));
}
}
您可以通过以下方式请求:
/home/display/123
-> parentid=123 和 currentid=123
/home/display/123/456
-> parentid=123 和 currentid=456