【问题标题】:Routing in ASP.NET MVC 2.0ASP.NET MVC 2.0 中的路由
【发布时间】:2011-02-27 20:56:22
【问题描述】:

我希望在我的 ASP.NET MVC 2.0 网站中创建一个非常简单的路由。我一直在谷歌上寻求帮助,但我能找到的所有示例都是针对非常复杂的路由。

基本上我希望我的主控制器中的所有页面都在域之后解析,而不是 /Home/

例如我想要http://www.MyWebsite.com/Home/LandingPage/

成为http://www.MyWebsite.com/LandingPage/

但仅对于 Home 控制器,我希望我的其他控制器正常运行。

我曾考虑为每个页面创建一个控制器,并且只使用一个索引,但我们需要大量这样的营销登陆页面,并且它会很快使网站加载每个页面的控制器,这不太理想.

【问题讨论】:

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


    【解决方案1】:

    一种方法是为每个着陆页设置单独的路径。另一种方法是使用单个路由,其约束与每个着陆页匹配(仅此而已)。

     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 机制每次都会使用反射来查看路由是否匹配(除非它缓存结果,我不认为它会这样做)。

    【讨论】:

    • 完美,帮助吨。谢谢!
    【解决方案2】:

    我认为你错过了默认路线。

        routes.MapRoute(
       "Default",                     // Route name
       "{controller}/{action}/{id}",  // URL with parameters
       new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
    );
    

    因此,当您键入 www.mywebsite.com 时,控制器、操作和 id 参数将具有以下值:

    controller : Home    
    action: Index    
    id : ""
    

    【讨论】:

      猜你喜欢
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多