使用静态名称mvc进行URL路由

时间:2015-03-27 07:12:22

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

我有一个控制器名称Dashboard,在该控制器中我有一个动作AdminDashboard。现在,默认情况下,此操作的网址将变为/Dashboard/AdminDashboard。我想将此操作映射到此网址/SupervisorDashboard

这就是我正在做的事情,但是没有找到它的说法

routes.MapRoute(
            name: "SupervisorDashboard",
            url: "SupervisorDashboard",
            defaults: new { controller = "Dashboard", action = "AdminDashboard" }
        );

以及如何使用Url.Action

重定向到此页面

Global.asax中

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "SupervisorDashboard",
            url: "SupervisorDashboard",
            defaults: new { controller = "Dashboard", action = "AdminDashboard" }
        );

    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

1 个答案:

答案 0 :(得分:2)

您是否已将此新路线定义放在默认路线之前?路线的评估顺序与注册顺序相同。如果您在任何自定义路线之前放置默认路线,它将被使用(并且因为您可能在代码中没有SupervisorDashboardController,所以将返回404。)

如果路由按正确的顺序定义,

Url.Action应该可以正常工作。

因此,对于这种情况,RouteConfig应该如下所示:

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

        // this one match /SupervisorDashboard only
        routes.MapRoute(
            name: "SupervisorDashboard",
            url: "SupervisorDashboard",
            defaults: new { controller = "Dashboard", action = "AdminDashboard" }
        );

        // should be last, after any custom route definition
        routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
      );
    }
}