Asp.Net:从URL中删除操作名称

时间:2015-11-15 04:33:41

标签: asp.net routing routes

我正在尝试创建允许我使用

的路由规则

http://localhost:*****/Profile/2

而不是

http://localhost:*****/Profile/Show/2

访问页面。我目前有一个路由规则,可以在访问页面时成功删除索引。我如何对此应用相同的概念?

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

1 个答案:

答案 0 :(得分:2)

我有几个问题需要澄清你想要做什么。因为创建自定义路线可能会产生一些意想不到的后果。

1)您是否只希望此路由应用于Profile控制器?

尝试在默认路线之前添加此路线..

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

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

这条新路线完全摆脱了Profile控制器中的Index和其他操作。该路由也仅适用于Profile控制器,因此您的其他控制器仍然可以正常工作。

您可以将正则表达式添加到" id"定义,以便只有在id为数字时才使用此路由,如下所示。这样您就可以再次使用Profile控制器中的其他操作。

   routes.MapRoute(
        name: "Profile",
        url: "Profile/{id}",
        defaults: new { controller = "Profile", action = "Show" }
        defaults: new { id= @"\d+" }
        );

此外,测试各种网址以查看每个网址将使用哪条路线是个不错的主意。转到NuGet并添加" routedebugger"  包。您可以在http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx/

获取有关如何使用它的信息