MVC RouteConfig,路由确定的控制器

时间:2015-04-06 17:30:53

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

我希望仅使用{action} {id}访问我的主要页面(索引,关于,联系...),而是访问{controller} {action} {id}的其他人。例如:

A principal page: myweb.com/index
No principal page: myweb.com/Account/Login

我已经搜索了但我不知道它是如何完成的。

这是我的RouteConfig

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

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

        /*routes.MapRoute(
            "Account",
        "Account/{AccountId}",
        new { action = "Index", controller = "Course" }
        );*/

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

        /*routes.MapRoute(
        "Account",
        "Account/{courseId}",
            //new { action = "Index", controller = "Course" }
        new { controller = "Home", action = "Index" }
        );*/
        //routes.Add()
    }
}

2 个答案:

答案 0 :(得分:0)

请参阅示例:

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

        // Principal pages have unique route per each page.
        // Methods About and Contact should be implemented in HomeController.
        routes.MapRoute(
            name: "About",
            url: "about",
            defaults: new { controller = "Home", action = "About" }
        );

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

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

答案 1 :(得分:0)

如下所示更改您的路线配置,但您必须在一个控制器中将所有主要操作称为PrincipalController,因为您的路线中没有控制器。

始终在低前置路线之前映射高优先级路线。

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

        routes.MapRoute(
            name: "Principal",
            url: "{action}/{id}",
            defaults: new { controller = Princpal", action = "Index", id = UrlParameter.Optional }

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