1. http://www.cnblogs.com/yukaizhao/archive/2010/05/20/urlrouting_asp_net_40.html
2. http://www.cnblogs.com/oec2003/archive/2010/07/27/1785862.html
1. Url Routing 的通常用法
UrlRouting在Asp.Net Mvc项目中被广泛使用,在Mvc中很好用,所以移植到了webform中,我们先看下在webform中的使用方式
假定一个使用场景:我们需要做博客每日文章的页面,我们希望的url地址是:
/archive/2010/05/10/default.aspx
这个地址将被映射到~/posts.aspx文件上
要使用UrlRouting,需要将UrlRouting的规则注册到RouteTable中,如下Global文件中注册Routing规则的代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public
static
void
RegisterRoutes(RouteCollection routes)
{
routes.Ignore(
"{resource}.axd/{*pathInfo}"
);
routes.MapPageRoute(
"blogs"
,
//给这个UrlRouting规则起一个名字
"archive/{year}/{month}/{date}/default.aspx"
,
//希望的友好Url地址格式
"~/blogs.aspx"
,
//映射到的aspx页面路径
false
,
//是否需要检查用户权限
new
RouteValueDictionary{ {
"year"
, DateTime.Now.Year },
{
"month"
, DateTime.Now.Month },
{
"date"
, DateTime.Now.Date}
},
//参数的默认值
new
RouteValueDictionary {
{
"year"
,
@"(19|20)\d{2}"
},
{
"month"
,
@"\d{1,2}"
},
{
"date"
,
@"\d{1,2}"
}
}
//参数的规则,我们在这里限制url中的年月日是我们想要的数据格式
);
}
void
Application_Start(
object
sender, EventArgs e)
{
//在Application_Start时注册的Routing规则
RegisterRoutes(RouteTable.Routes);
}
|
2. 在页面中使用UrlRouting参数值
1) 在后台代码中使用Route的值
1
2
3
4
5
6
|
protected
void
Page_Load(
object
sender, EventArgs e)
{
string
year = (
string
)RouteData.Values[
"year"
];
string
month = (
string
)RouteData.Values[
"month"
];
string
date = (
string
)RouteData.Values[
"date"
];
}
|
2) 在页面上使用
1
2
3
|
<
asp:Literal
ID
=
"literalYear"
runat
=
"server"
Text="<%$RouteValue:year %>"></
asp:Literal
>
-<
asp:Literal
ID
=
"literal1"
runat
=
"server"
Text="<%$RouteValue:month %>"></
asp:Literal
>
-<
asp:Literal
ID
=
"literal2"
runat
=
"server"
Text="<%$RouteValue:date %>"></
asp:Literal
>
|
3) 在DataSource中使用RouteParameter
1
2
3
4
5
6
|
<
asp:SqlDataSource
ID
=
"SqlDataSource1"
runat
=
"server"
ConnectionString="<%$ ConnectionStrings:TestDb %>"
SelectCommand="SELECT BlogID,BlogTitle FROM Blogs Where Category = @category">
<
SelectParameters
>
<
asp:RouteParameter
Name
=
"category"
RouteKey
=
"category"
/>
</
SelectParameters
>
</
asp:SqlDataSource
>
|
4) 在页面上显示RouteUrl
1
|
<
a
href='<%=GetRouteUrl("blogs",new {
year
=
2010
,
month
=
05
,
date
=
05
}) %>'>2010年5月1日的博客</
a
>
|