MVC路由在URL中删除/索引

时间:2012-11-26 15:39:10

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

我有一个在运行时生成的动态链接的动态列表,如下所示:

@Html.ActionLink(x.Name, "Index", "User", new { x.ID }, null)

所以我在用户控制器上点击了Index方法。

我还将RouteConfig.cs(它是一个MVC4应用程序)设置如下:

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

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

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

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

这为我提供了链接列表server/application/User/Index/1

我需要在列表生成和/或路由文件中将其更改为server/application/User/1

1 个答案:

答案 0 :(得分:11)

添加不需要操作但不会与其他路线冲突的路线

routes.MapRoute("User", "User/{id}", 
                         new { controller = "User", action = "Index" });