ASP.NET MVC中怎么去控制路由,這個想關的文章很多,我在這里就是自我總結一下,僅供參考。
1.我們新建一個項目,查看RouteConfig.cs,代碼如下:
1 public static void RegisterRoutes(RouteCollection routes) 2 { 3 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 4 5 routes.MapRoute( 6 name: "Default", 7 url: "{controller}/{action}/{id}", 8 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 9 ); 10 }
第3行,routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 表示忽略有擴展名 axd的路由,
你可以仿照它,如果你項目里有哪些文件是不攻外部訪問的,可以全部過濾掉。
1 routes.MapRoute( 2 name: "Default", 3 url: "{controller}/{action}/{id}", 4 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 5 );
這個就是最基本的路由控制了。表示首頁是HomeController里的ActionResult Index,默認路由參數為id
下面我們來改改這串代碼,如下:
1 ///首頁 2 routes.MapRoute( 3 "Index", // Route name 4 "{controller}/{action}", 5 new { controller = "Index", action = "Index", id = UrlParameter.Optional }, 6 new string[] { "SnsCWan.Controllers" } 7 );
有備注大伙應該看得懂,其中 new string[] { "SnsCWan.Controllers" } 里的SnsCWan是當前網站名稱,這個先注意一下。
1 ///PayStepIndex 2 routes.MapRoute( 3 "PayStepIndex", // Route name 4 "{controller}/{action}/{Method}/{id}.html", 5 new { controller = "PayStep", action = "Index", Method = UrlParameter.Optional, id = UrlParameter.Optional }, 6 new string[] { "SnsCWan.Controllers" } 7 );
這個是有控制多個參數的路由,你可以改 "{controller}/{action}/{Method}/{id}.html" 來設置你需要的路由方式。
下面我們新建一個Admin的Areas,表示站點的管理員部分,默認生成的代碼如下:
1 public override void RegisterArea(AreaRegistrationContext context) 2 { 3 context.MapRoute( 4 "Admin_default", 5 "Admin/{controller}/{action}/{id}", 6 new { action = "Index", id = UrlParameter.Optional } 7 ); 8 }
同一個網站里面,如果根目錄下的路由和Areas下的路由同時都路由到一個Index/Index,此時項目就會報錯,告訴你同時存在了2個路由,這個時候怎么處理呢? 如下:
1 context.MapRoute( 2 "Admin_default", 3 "Admin/{controller}/{action}/{id}", 4 new { controller = "Index", action = "Index", id = UrlParameter.Optional }, 5 new string[] { "SnsCWan.Areas.Admin.Controllers" } 6 );
特別主意 new string[] { "SnsCWan.Areas.Admin.Controllers" } ,這個和根目錄下的路由的區別,它表示指定 SnsCWan網站下的Areas區域的Admin控制器,
這樣,路由間就不會再產生沖突了。
總得配置路由就是這些,具體怎么去設置更加美觀的url還有待你更具創意的想法。
本群提供ASP.NET MVC,EF,LINQ,WEB API技術支持,不在乎人多,在乎人精。
ASP.NET MVC群 171560784
誠邀各路高手、初學者加入。