【问题标题】:MVC4 Default RoutesMVC4 默认路由
【发布时间】:2015-02-16 22:38:04
【问题描述】:

我有以下两条路线,当用户登陆主页时,它会抛出 404。我错过了什么明显的东西吗?我希望他们转到 Home 控制器...

        routes.MapRoute(
            name: "Default",
            url: "Home/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "Coin.Web.Controllers" }
        );

        routes.MapRoute(
            name: "Organization",
            url: "{organization}/{controller}/{action}/{id}",
            defaults: new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "Coin.Web.Controllers" }

提前致谢!

【问题讨论】:

  • 在不知道您要使用的网址是什么的情况下,很难确定出了什么问题。

标签: asp.net-mvc asp.net-mvc-4 routes


【解决方案1】:

是的,路由 / 将在“默认”路由上丢失(因为它需要在 URL 中添加 /Home 段),就像您设置它的方式一样,它也会丢失“组织”路由(因为您没有定义默认组织)。这就是你得到 404 的原因。

您可以通过为主页显式添加路由来修复它:

    routes.MapRoute(
        name: "Home",
        url: "",
        defaults: new { controller = "Home", action = "Index" },
        namespaces: new[] { "Coin.Web.Controllers" }
    );

    routes.MapRoute(
        name: "Default",
        url: "Home/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        namespaces: new[] { "Coin.Web.Controllers" }
    );

    routes.MapRoute(
        name: "Organization",
        url: "{organization}/{controller}/{action}/{id}",
        defaults: new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional },
        namespaces: new[] { "Coin.Web.Controllers" }

仅供参考 - 通常最好将更具体的路线放在不太具体的路线之前。也就是说,“组织”路线应该先走,而您应该不理会“默认”路线。但是您需要定义一个明确的段或约束,以强制错过“组织”路线或使用多个组织路线以使其发挥作用。

【讨论】:

    猜你喜欢
    • 2013-10-03
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2010-11-01
    相关资源
    最近更新 更多