2015-11-15 20 views
1

我想創建一個路由規則,允許拆除行動名字我用Asp.Net:從URL

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

我有幾個問題來澄清你正在嘗試做什麼。因爲創建自定義路線可能會有一些意想不到的後果。

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控制器,所以您的其他控制器仍然可以正常工作。

您可以將正則表達式添加到「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/

+0

得到有關如何使用它的信息。 「但除此之外按預期工作。 – Anon