MVC路由映射在Html.RenderAction上获得异常:路由表中的路由与提供的值不匹配

时间:2014-04-23 07:12:17

标签: asp.net-mvc routing asp.net-mvc-5

我使用ASP.NET MVC 5,除Home/index之外的所有操作都是我的路线图:

 routes.MapRoute(
                name: "randomNumber",
                url: "{controller}/{randomNumber}/{action}",
                defaults: new { },
                constraints: new { randomNumber = @"\d+" }
            );

首页:Home/Index我不想使用{randomNumber}

所以我认为第一个解决方案是:

routes.MapRoute(
                 name: "Default",
                 url: "{controller}/{action}",
                 defaults: new { controller = "Home", action = "Index" }
            );

此路线图解决了我的问题,但又导致了另一个问题:客户端可以在没有{randomNumber}的情况下访问其他操作,但我只想在Index操作Home随机数。

另一个解决方案是:

  routes.MapRoute(
                     name: "Default",
                     url: "Home/Index",
                     defaults: new { controller = "Home", action = "Index" }
                );

但是使用此地图我无法使用根网址访问Home/index,我需要使用根网址访问Home/index,如下所示: www.mydomainaddress.com

最后我发现了这个:

   routes.MapRoute(
                     name: "Default",
                     url: "",
                     defaults: new { controller = "Home", action = "Index" }
                );

但是我在No route in the route table matches the supplied values.这个文件的index.cshtml文件中得到了例外:@{Html.RenderAction("ArchiveList", "Home");}RenderAction

我不知道我添加的路线图和 routes.MapRoute( name: "Default", url: "", defaults: new { controller = "Home", action = "Index" } ); routes.MapRoute( name: "HomeActions", url: "Home/{action}", defaults: new { controller = "Home" } ); 帮手的关系?

但如果我添加以下两个路线图,一切都会好的:

Default

但是我不能添加你知道的第二个地图路线(我需要用随机数访问所有动作)

我无法理解添加RenderAction地图时发生了什么,以及与{{1}}帮助相关的内容?

有人对此有任何想法吗?有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我已经在MVC5中使用了这种语法,它可以工作:

        routes.MapRoute(
            name: "HomePage",
            url: "",
            defaults: new { controller = "Home", action = "Index" }
            );

此语法允许您使用www.mydomainaddress.com访问您的主页,但如果您尝试使用www.mydomainaddress.com/home/index

,它将无法正常工作

我不明白为什么它不适合你。您可以尝试重新安排订单或MapRoutes定义(将" HomePage"路线放在" randomNumber"路线之后)

我看到了你修改过的问题。我知道您希望能够对家庭控制器使用任何操作,并且不希望能够将randomNumber用于HomeController。

这可能更适合你(也禁用Home控制器的randomNumber路由):

        routes.MapRoute(
               name: "HomePage",
               url: "",
               defaults: new { controller = "Home", action = "Index" }
          );

        routes.MapRoute(
                name: "HomeActions",
                url: "Home/{action}",
                defaults: new { controller = "Home", action = "Index" }
            );

        routes.MapRoute(
           name: "randomNumber",
           url: "{controller}/{randomNumber}/{action}",
           defaults: new { },
           constraints: new { randomNumber = @"\d+", controller = @"^((?!Home).)*$" }
       );