標籤:style blog http io color ar os 使用 sp
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 { {"controlls","*"}, {"action","*"} };//定義一個路由字典 RouteTable.Routes.MapPageRoute("defaults", "{controller}/{action}", "~/RouteMapping.aspx", true, defaults);//進行預設的路由映射,在整個類比路由的過程中,所有的使用者請求都將交給RouteMapping.aspx這WebForm頁面進行處理。}
三、使用者請求"{controller}/{action}"格式的Url路徑,如http://localhost:1673/Abc ,那麼將顯示Abc.aspx頁面的內容。
僅僅在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 { } } } }
一、ASP.NET MVC 路由(一)--- ASP.NET WebForm路由類比