asp.net 4.0 URL Routing 体验

还是和刚才一样,做些小实验,感受一下,新版本所带来的便利,也是自我学习一下。其他大的道理也不用说了。

 

步骤1:

在Global.asax文件里,添加相应的规则

  void Application_Start(object sender, EventArgs e)
    {
        // 在应用程序启动时运行的代码
        RegisterRoutes(System.Web.Routing.RouteTable.Routes);
    }
    void RegisterRoutes(System.Web.Routing.RouteCollection routes)
    {
        routes.MapPageRoute("MyFriendlyName", "Report/{year}", "~/a.aspx");
    }

 

在default.aspx页里加上    <a href="Report/2010">test</a>,点击后,注意一下地址栏。再看一下a.aspx页面的内容。


public partial class a : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(RouteData.Values["year"] as string);

        if (Request.QueryString["category"] != null)
        {
            Response.Write(Request.QueryString["category"].ToString());
        }
    }
}

 

 

也可以自己生成友好名称:

  RouteValueDictionary parameters = new RouteValueDictionary()
        {
            { "year", "2008" },
            { "category", "goods" },
              { "customer", "hello" }
        };

        VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "MyFriendlyName", parameters);
        this.HyperLink1.NavigateUrl = vpd.VirtualPath;

 

这个时候地址就变成了:http://localhost:9319/WebSite1/Report/2008?category=goods&customer=hello

看一下category,customer,这二个,就是相应的参数了。

 

应该来说,还是比较方便的。以前还需要在IIS里做相应的配置才可以达到相应的功能。

 

 

 

posted @ 2010-06-03 15:25  greystar  阅读(149)  评论(0编辑  收藏  举报