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

 

posted on 2010-11-16 16:57  Magic.Z  阅读(4493)  评论(5编辑  收藏  举报