在.Net 4.0之前我们为了做出搜索引擎友好的,对用户也友好的url都是需要自己实现Url重写,现在不需要了,.Net 4.0为我们做这一切。UrlRouting之所以称之为Routing是因为它不但实现了Url重写还可以通过参数得到重写后的Url在页面上使用。
1. Url Routing 的通常用法
UrlRouting在Asp.Net Mvc项目中被广泛使用,在Mvc中很好用,所以移植到了webform中,我们先看下在webform中的使用方式
假定一个使用场景:我们需要做博客每日文章的页面,我们希望的url地址是:
/archive/2010/05/10/default.aspx
这个地址将被映射到~/posts.aspx文件上
要使用UrlRouting,需要将UrlRouting的规则注册到RouteTable中,如下Global文件中注册Routing规则的代码
01 | public static void RegisterRoutes(RouteCollection routes) |
03 | routes.Ignore( "{resource}.axd/{*pathInfo}" ); |
05 | routes.MapPageRoute( "blogs" , |
06 | "archive/{year}/{month}/{date}/default.aspx" , |
09 | new RouteValueDictionary{ { "year" , DateTime.Now.Year }, |
10 | { "month" , DateTime.Now.Month }, |
11 | { "date" , DateTime.Now.Date} |
13 | new RouteValueDictionary { |
14 | { "year" , @"(19|20)\d{2}" }, |
22 | void Application_Start( object sender, EventArgs e) |
25 | RegisterRoutes(RouteTable.Routes); |
2. 在页面中使用UrlRouting参数值
1) 在后台代码中使用Route的值
1 | protected void Page_Load( object sender, EventArgs e) |
3 | string year = ( string )RouteData.Values[ "year" ]; |
4 | string month = ( string )RouteData.Values[ "month" ]; |
5 | string date = ( string )RouteData.Values[ "date" ]; |
2) 在页面上使用
1 | < asp:Literal ID = "literalYear" runat = "server" Text="<%$RouteValue:year %>"></ asp:Literal > |
2 | -< asp:Literal ID = "literal1" runat = "server" Text="<%$RouteValue:month %>"></ asp:Literal > |
3 | -< asp:Literal ID = "literal2" runat = "server" Text="<%$RouteValue:date %>"></ asp:Literal > |
3) 在DataSource中使用RouteParameter
1 | < asp:SqlDataSource ID = "SqlDataSource1" runat = "server" ConnectionString="<%$ ConnectionStrings:TestDb %>" |
2 | SelectCommand="SELECT BlogID,BlogTitle FROM Blogs Where Category = @category"> |
4 | < asp:RouteParameter Name = "category" RouteKey = "category" /> |
4) 在页面上显示RouteUrl
1 | < a href='<%=GetRouteUrl("blogs",new { year = 2010 , month = 05 , date = 05 }) %>'>2010年5月1日的博客</ a > |
3. UrlRouting和UrlRewrite的区别
UrlRouting相对于Url重写是一个比较新的事物,UrlRouting的长处是可以做双向转换,既可以做url重写,还可以根据一些参数获得重写后的Url地址,但是它也有自己的不足之处,比如说如果你想连域名一起重写,比如博客地址yukaizhao.cnblogs.com这样的重写,UrlRouting就做不到了,只能用UrlRewrite。