代码之家  ›  专栏  ›  技术社区  ›  erlando

如何配置ASP.NETMVC路由在“主页”上隐藏控制器名称?

  •  2
  • erlando  · 技术社区  · 14 年前

    ASP.NET MVC Routing with Default Controller

    我有一个类似的要求,即我的最终用户不希望在登陆的url或他们的应用程序的“主页”中看到控制器名称。

    我有一个控制器叫 DeviceController 我想成为“主页”控制器。此控制器有许多操作,我希望使用如下URL:

    http://example.com  -> calls Index()  
    http://example.com/showdevice/1234 -> calls ShowDevice(int id)  
    http://example.com/showhistory/1224 -> calls ShowHistory(int id)  
    

    我还需要为这个控制器生成的链接,以省去 /device url的一部分。

    例如,我还有一些其他控制器 BuildController :

    http://example.com/build  
    http://example.com/build/status/1234  
    http://example.com/build/restart/1234  
    

    等等。这些控制器的URL都很好。

    问题是,即使在研究了上面提到的问题的答案之后,我似乎还是无法理解这个问题的答案。

    我在用ASP.NETMVC2型。

    2 回复  |  直到 8 年前
        1
  •  6
  •   Max Toro    14 年前

    试试这个:

       private void RegisterRoutes(RouteCollection routes) {
    
          routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
          routes.MapRoute("default", "{controller}/{action}/{id}",
             new { action = "index", id = "" },
             // Register below the name of all the other controllers
             new { controller = @"^(account|support)$" });
    
          routes.MapRoute("home", "{action}",
             new { controller = "device", action = "index" });
       }
    

    e、 克/福

    foo 不是控制器,则它被视为 device 控制器。

        2
  •  0
  •   Rahul    9 年前

    第一步: 创建管线约束。

    public class RootRouteConstraint<T> : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name.ToLower());
            return rootMethodNames.Contains(values["action"].ToString().ToLower());
        }
    }
    

    第二步:

    routes.MapRoute(
                    "Root",
                    "{action}",
                    new {controller = "Home", action = "Index", id = UrlParameter.Optional},
                    new {isMethodInHomeController = new RootRouteConstraint<HomeController>()}
                    );
    
    
    routes.MapRoute(
                    "Default",
                    "{controller}/{action}/{id}",
                    new
                    {controller = "Home", action = "Index", id = UrlParameter.Optional}
                    );
    

    example.com/关于, example.com/联系方式

    这只会影响HomeController的url。所有其他控制器都将具有默认路由功能。