我正在寻找在ASP.NET MVC 2.0网站中做一个非常简单的路由。我一直在寻找帮助,但是我能找到的所有示例都是针对真正复杂的路由的。
基本上,我想让Home Controller中的所有页面都在域之后解析,而不是/ Home /
例如我想要http://www.MyWebsite.com/Home/LandingPage/
成为http://www.MyWebsite.com/LandingPage/
但是仅对于Home Controller ,我希望其余 Controller 正常运行。
我曾考虑过为每个 Controller 创建一个 Controller 并仅使用一个索引,但是像这样,我们需要大量的登陆页面来进行市场营销,这样会使网站上每个 Controller 都装载了单个页面,这不理想。
最佳答案
一种方法是为每个目标网页设置单独的路线。另一种方法是让一条路线的约束条件与每个目标网页相匹配(而没有其他约束)。
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解决方案与之类似,不同之处在于您只有一 strip 有自定义约束的路由,该路由会评估适当的路由值是否与HomeController上的方法之一匹配,如果匹配,则将 Controller 和操作替换为“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机制每次都会使用反射来查看路由是否匹配(除非它缓存结果,但我认为这不行)。
关于asp.net-mvc - 在ASP.NET MVC 2.0中进行路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2975642/