一、ASP.NET MVC 路由(一)--- ASP.NET WebForm路由模擬
阿新 • • 發佈:2018-12-27
ASP.NET WebForm 應用,使用者請求的是物理檔案,其中包括靜態頁面和動態頁面,在Url中的顯示都是伺服器中一個物理檔案的相對路徑。但是ASP.NET MVC就不同了,使用者請求的是Controller中一個Action方法,這種請求是通過路由將Url對映到相對的Controller和Action中。
ASP.NET MVC是在Application_Start時,定義了路由的規則,當用戶使用規定的路由規則進行訪問時,就會通過路由對映的方式實現使用者完整的Url訪問。下面我們就開始使用Asp.net WebForm進行簡單的路由模擬。
一、我們新建一個ASP.NET Empty Web Application
二、新增一個Global.asax檔案,並在Application_Start事件中模擬ASP.NET MVC寫路由程式碼。(注:Application_Start 事件是當整個應用程式部署到IIS等伺服器,啟動應用程式池時執行一次)
protected void Application_Start(object sender, EventArgs e) { var defaults = new RouteValueDictionary { {"controller","*"}, {"action","*"} };//定義一個路由字典 RouteTable.Routes.MapPageRoute("defaults", "{controller}/{action}", "~/RouteMapping.aspx", true, defaults);//進行預設的路由對映,在整個模擬路由的過程中,所有的使用者請求都將交給RouteMapping.aspx這WebForm頁面進行處理。 }
三、使用者請求"{controller}/{action}"格式的Url路徑,如http://localhost:1673/Abc
僅僅在Application_Start中配置資訊是達不到上圖的效果的。上圖配置的路由資訊僅僅是映射了RouteMapping.aspx這一個頁面,要想達到較好的效果,需要對RouteMapping.as頁面獲取到的"{controller}/{action}"資訊進行稍微的處理。
protected void Page_Load(object sender, EventArgs e) { string controller = RouteData.Values["controller"] as String;//獲取到路由表中的controller資料 //string action = RouteData.Values["action"] as String; if (!String.IsNullOrEmpty(controller)) { if (controller == "*") { Server.Transfer("Default.aspx");//Url地址如http://localhost:1673/則訪問預設頁 } else { try { Server.Transfer(controller + ".aspx");//使用Server.Transfer進行伺服器端重定向,進而顯示了controller對應的頁面方法。 } catch { } } } }