我如何路由到localhost:2233 /用户名?

时间:2015-03-21 07:33:15

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

在mvc 4中,我试图路由到这样的http://localhost:22128/username。在我的route.config

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

为此,我需要更改url格式吗?我怎么路线?有人可以帮我解决这个问题吗?我对此非常困惑。

修改

我试过这个

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

        routes.MapRoute(
        "UserProfile",
        "{username}",
        new { controller = "Profile", action = "Index", username = string.Empty }
        );

但仍然没有在索引方法中找到配置文件控制器。

1 个答案:

答案 0 :(得分:1)

路线订单特定。他们是从注册到最后一条路线的第一条路线尝试的。

由于默认路由匹配每个具有0,1,2或3个段的URL,因此不会使用任何这些长度定义后的URL。

因此,您需要在UserProfile路线之前定义Default路线。

routes.MapRoute(
    "UserProfile",
    "{username}",
    new { controller = "Profile", action = "Index", username = string.Empty }
);

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