在 ASP.NET WebForm 中使用 Route

來源:互聯網
上載者:User

使用過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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.