使用過ASP.NET MVC的同學可能對Route已經有些接觸,在ASP.NET WebForm中為實作類別似的功能也許會使用URL Rewrite。本文將介紹在ASP.NET WebForm中使用Route。
1. 找到Global.asax檔案,如果沒有這個檔案就建立一個。
2. 添加RegisterRoutes方法
代碼
1 public static void RegisterRoutes(RouteCollection routes)
2 {
3 // 預設頁
4 routes.MapPageRoute(
5 "Defautl",
6 "",
7 "~/Folder1/WebForm1.aspx"
8 );
9
10 // 對{folder}/{webform}形式的URL進行路由
11 routes.MapPageRoute(
12 "WebForm1",
13 "{folder}/{webform}",
14 "~/{folder}/{webform}.aspx"
15 );
16
17 // 對{folder}/{page}形式的URL進行路由(帶參數)
18 routes.MapPageRoute(
19 "WebForm2",
20 "{floder}/{webform}/{parameter}",
21 "~/{floder}/{webform}.aspx"
22 );
23
24 }
3. 在Application_Start方法中使用RegisterRoute方法。
1 protected void Application_Start(object sender, EventArgs e)
2 {
3 RegisterRoutes(RouteTable.Routes);
4 }
如果要擷取URL中的參數,可以參考下面的代碼
1 string parameter = Page.RouteData.Values["parameter"] as string;
它將擷取預留位置為parameter的參數。如~/Folder2/WebForm3/abc可擷取parameter參數的值是abc,但是如果遇到~/Folder2/WebForm3?parameter=abc似乎擷取不到parameter的參數值。可以使用
1 string parameter = Request.Params["parameter"] as string;
來擷取。
樣本下載
本文適用於 ASP.NET 4