具有相同网址的多个路由

时间:2016-03-25 19:45:22

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

我目前在RouteConfig.cs中有以下内容:

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

        routes.MapRoute(
            name: "Identity",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Profile", action = "Identity" }
        );

我正在尝试在Action方法中使用以下内容:

return RedirectToRoute("Identity", new { @id = id });

但它似乎没有去那里,当我与Fiddler核实时,我看到请求回到我当前所在的同一页面,它似乎正在达到默认路线。无论如何强制它获得一个身份,即使他们的网址是相同的,我想用它来迫使用户在需要时使用另一个控制器。

2 个答案:

答案 0 :(得分:2)

MVC将在找到匹配后立即停止寻找路线。在您的情况下,它将按以下顺序查看:1。)默认2.)标识。

如果要创建具有相同模式的特定路径,可以使用以下代码实现:

routes.MapRoute(
    name: "Identity",
    url: "Profile/{action}/{id}",
    defaults: new { controller = "Profile", action = "Identity" }
);

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

答案 1 :(得分:1)

您无需将用户“强制”为其他控制器。使用RedirectToAction方法是一种很好的做法,因此您可以提供要将用户带到的控制器和操作。

@ thiag0提供的解决方案无效。

使用以下

return RedirectToAction("Identity", "Profile", new { id = 5 });

并在配置文件控制器中,确保您可以接受参数

    public ActionResult Identity(int id)
    {
        return View();
    }

和在RouteConfig.cs中

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

            routes.MapRoute(
            name: "Identity",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Profile", action = "Identity"}
            );
相关问题