【问题标题】:Another MVC routing problem另一个MVC路由问题
【发布时间】:2011-06-03 11:34:26
【问题描述】:

有一天我会理解路由,但这就是我所拥有的:

public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("favicon.ico");



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

        }

如果我去http://localhost 一切正常

如果我去http://localhost/Home/Index/1234 一切都好

如果我去http://localhost/1234它是404的

我尝试了 Phil Haack 的路由调试器,但因为它抛出 404 路由调试器不起作用。

我必须在 RegisterRoutes 中做什么才能让http://localhost/1234 工作

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:
    routes.MapRoute(
        "LicenceCode",
        "{LicenceCode}"
        new { controller = "Home", action = "Index", LicenceCode = UrlParameter.Optional } // Parameter defaults
    );
    

    然后/1234 将路由到Home 控制器的Index 操作:

    public ActionResult Index(string licenceCode)
    {
        ...
    }
    

    【讨论】:

    • 这是我当前路线的补充吗?我有其他控制器,所以我需要能够去localhost/basket 例如
    • @Jon,你不能。您如何期望路由引擎在/foo/basket 之间消除歧义,在第一种情况下foo 表示许可证代码,在第二种情况下表示控制器?这根本没有意义。您可以做的是指定一个正则表达式路由约束作为MapRoute 的第四个参数,例如,如果您的许可证号遵循某种模式。这样,您可以在默认路由之前拥有许可路由,并且如果满足约束,许可路由将匹配。
    【解决方案2】:

    您必须使用以下根而不是您的:

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

    【讨论】:

    【解决方案3】:

    我面前没有 Visual Studio,但我认为应该是

    routes.MapRoute(
        "Default2",
        "{LicenceCode}",
        new { controller = "Home", action = "Index", LicenceCode = UrlParameter.Optional }
    );
    

    你肯定想把它放在你的路由注册中,因为我想这会劫持很多路径。

    【讨论】:

      【解决方案4】:

      如上所述设置默认路由 路线.MapRoute( "Default", // 路由名称 "{LicenceCode}", // 带参数的 URL new { controller = "Home", action = "Index", LicenceCode = UrlParameter.Optional } // 参数默认值 );

      但是不要在 global.asax 中添加 1,000 行路由

      对于其他路由,通过视图和控制器进行处理。示例:

      1. 在控制器中:在 ActionResults 方法中,您可以执行 return RedirectToAction("ClientEnrollment", "Cis");

      2. 在视图中:有一个链接 @Html.ActionLink("Select", "ClientDetails", "Cis", new { id = item.ClientId }, null) |

      【讨论】:

        猜你喜欢
        • 2011-07-31
        • 1970-01-01
        • 2016-11-09
        相关资源
        最近更新 更多