The support for Routing is provided in asp.net 4.0. By using the routing technology, we can easily build a friendly url, so that users can understand and optimize SEO.
1. Register a route table in Global
Void Application_Start (object sender, EventArgs e)
{
// Code that runs when the application starts
This. RegisterRoutes (RouteTable. Routes );
}
Void RegisterRoutes (RouteCollection routes)
{
Routes. MapPageRoute ("BookDetails ",
"Book/details/{index}/{keyword }",
"~ /Book/details. aspx ",
False,
New RouteValueDictionary ()
{
{"Index", "1 "},
{"Keyword ",""}
}
);
}
2. Generate a URL
One method is hard encoding. According to the above rules, we can simply write a matching URL:/book/details/23/asp
Of course, the hard coding method is not recommended, and it is not easy to maintain our rules. We recommend that you use VirtualPathData to generate a virtual path. When using it, you must provide the corresponding route name and parameter list:
RouteValueDictionary parameters = new RouteValueDictionary()
{
{"index", "19" },
{"keyword", "Tom" },
};
VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "BookDetails", parameters);
hlCreateURL.NavigateUrl = vpd.VirtualPath;
In this Code, vpd. VirtualPath is the virtual URL generated according to the BookDetails rule.
3. Get the parameter value
After using Routing, we can no longer use Request. QueryString
Set to obtain URL parameters. This is because Routing does not rewrite the URL, but only processes the URL to the specified page.
At this time, we need to use the Routing method to obtain the webpage parameters.
this.Page.RouteData.Values["index"];
this.Page.RouteData.Values["keyword"];
The whole process is like this. First, there must be rules, then there must be an access address, and finally we must be able to get the actual parameters.
---------------------------------------------------------
Ps. attach some learning resources from Lao Zhao's blog and MSDN:
Http://msdn.microsoft.com/zh-cn/library/dd329551.aspxhttp://msdn.microsoft.com/zh-cn/library/cc668201.aspxhttp://www.cnblogs.com/JeffreyZhao/archive/2009/09/29/aspnet-routing-request-processing.htmlhttp://www.cnblogs.com/JeffreyZhao/archive/2009/09/30/things-about-aspnet-routing.html