一种方法是为每个着陆页设置单独的路径。另一种方法是使用单个路由,其约束与每个着陆页匹配(仅此而已)。
routes.MapRoute(
"LandingPage1"
"landingpage1/{id}",
new { controller = "home", action = "landingpage", id = UrlParameter.Optional } );
routes.MapRoute(
"LandingPage2"
"landingpage2/{id}",
new { controller = "home", action = "landingpage2", id = UrlParameter.Optional } );
请注意,您也可以通过一些反思来做到这一点(未经测试)。
foreach (var method on typeof(HomeController).GetMethods())
{
if (method.ReturnType.IsInstanceOf(typeof(ActionResult)))
{
routes.MapRoute(
method.Name,
method.Name + "/{id}",
new { controller = "home", action = method.Name, id = UrlParameter.Optional } );
}
}
RouteConstraint 解决方案与此类似,只是您有一个带有自定义约束的路由,该约束评估适当的路由值是否与 HomeController 上的方法之一匹配,如果匹配,则将控制器和操作替换为“home " 和匹配的值。
routes.MapRoute(
"LandingPage",
"{action}/{id}",
new { controller = "home", action = "index", id = UrlParameter.Optional },
new LandingPageRouteConstraint()
);
public LandingPageRouteContstraint : IRouteConstraint
{
public bool Match
(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection
)
{
// simplistic, you'd also likely need to check that it has the correct return
// type, ...
return typeof(HomeController).GetMethod( values.Values["action"] ) != null;
}
}
请注意,即使您使用反射,每页路由机制也只会执行一次。从那时起,您每次都进行简单的查找。 RouteConstraint 机制每次都会使用反射来查看路由是否匹配(除非它缓存结果,我不认为它会这样做)。