asp.net-mvc - 在ASP.NET MVC 2.0中进行路由

标签 asp.net-mvc model-view-controller asp.net-mvc-2 routing routes

我正在寻找在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/

相关文章:

c# - 如何在 ASP.NET MVC 上同时执行 Azure Active Directory 单点登录和表单例份验证

asp.net-mvc - MVC 中 "Master Page"逻辑应该放在哪里?

asp.net-mvc-2 - 如何在 ASP.NET MVC 中实现自定义主体和身份?

asp.net-mvc - 检查 MVC4 中 Jquery AutoComplete 组合框中的 SelectIndexChange/Blur 事件

c# - 哪个是避免魔术字符串键的更好方法?在类中使用字符串常量键还是使用枚举?

sql-server - 将 ASP.NET MVC 应用程序的 IIS 7.5 应用程序池标识配置为 SQL Server 2008 R2 上的登录名

asp.net-mvc-2 - 为什么 mvc Html.HiddenFor 不呈现我的字段?

java - 为 Liferay 搜索容器设置 MVC renderParameter

java - 为什么使用服务层而不是 spring Controller 的帮助类?

asp.net-mvc - 使用 mvc 2 将链接标签添加到母版页