.net4.0(VS2010平台) url重写

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 >

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值