RedirectToAction() (MVC5) 的意外行为

Unexpected behaviour of RedirectToAction() (MVC5)

我在尝试使用 RedirectToAction() 时遇到问题。

在我的 RouteConfig.cs 我有这样的东西:

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

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

从我的控制器,如果我尝试这样做:

    public ActionResult Contact()
    {
        return RedirectToAction("About", "Home");
    }

我明白了 URL:

http://localhost:51547/myroot/Home/About

这不是我所期望的。如果我试试这个:

return RedirectToRoute("Default", new { controller = "Home", action = "About" });

我明白了 URL:

http://localhost:51547/Home/About

这对我来说很有意义。

谁能解释为什么 RedirectToActionmyroot/ 前缀添加到 URL 而不是匹配 Default 路由?

谢谢!

请将您的路线顺序更改为

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

这可能有效...未测试

return RedirectToAction("action", "controller", new { area = "" });