In the
asp.net4.0 we use routing to easily optimize http://localhost/Customer.aspx?Id=1 into http://localhost/Custome/1 form, and here's a concrete example.
First, create an empty asp.net 4.0 Web form project, create Global.asax files, and in the Glolal class, we add the following code:
Namespace easyurl { public class Global : System.Web.HttpApplication { protected void application_start (object sender, eventargs e) { registerroutes (
Routetable.routes); } public Static void registerroutes (routecollection routecollection) { // Routecollection.mappageroute ("Routeforcustomer", "Customer/{id}", "~/customer.aspx") // can use the above, but it is best to use the following, so you can limit the ID number &nbSp; routecollection.mappageroute ("Routeforcustomer", "Customer/{id}", "~/" Customer.aspx ", true, null, new routevaluedictionary (new { id = " \\d+ ")
&NBSP})); }  }}
Then add a customer.aspx file, the code is very simple, as follows:
public partial class Customer:page
{
protected void Page_Load (object sender, EventArgs e)
{
String id = page.routedata.values["id"]. ToString ();
Response.Write ("
Notice that we are using the page.routedata.values["Id" to take the value.
In this way, when we visit HTTP://LOCALHOST/CUSTOMER/1, we are presented with the desired page:
Customer Detail Page
Customerid:1
Extend a
In fact, the above effect has been very simple to achieve, but we found that we have to use the page.routedata.values["id" This form to take the value, rather than we usually use the page.querystring["id" to take, then we can do this?
We know that the value of the request before Pageload is initialized well, so if we're going to use this approach, We have to add the Routedata.values value to the QueryString before this cycle, so let's try to build a pagebase base class (all of the following pages will inherit this class), and the code is as follows:
Public abstract class PageBase:System.Web.UI.Page
{
protected override void Oninitcomplete (EventArgs e)
{
base. Oninitcomplete (e);
Page.RouteData.Values.Keys.ToList (). ForEach (Key =>
{
Request.QueryString.Add (key, Page.routedata.values[key). ToString ());
});
}
}
After
ran, we found the Yellow Pages:
Exception Details:System.NotSupportedException:Collection is read-only.
Source Error:
Line 20: Page.RouteData.Values.Keys.ToList (). ForEach (key =>
Line 21: {
Line 22 : REQUEST.QUERYSTRING.ADD (Key, Page.routedata.values[key]. ToString ());
Line 23: });
Line 24: }
Originally QueryString This collection is read-only, through Old Zhao's article a more complete keyword filtering solution Let's rewrite the code:
public static class globalvalues { public static propertyinfo
NameObjectCollectionBaseIsReadOnly; static globalvalues () {
type type = typeof (NameObjectCollectionBase); nameobjectcollectionbaseisreadonly = type. GetProperty ( "IsReadOnly", BindingFlags.Instance |
BindingFlags.NonPublic);    &NBSP}} public abstract class pagebase : system.web.ui.page { protected override void oninitcomplete (eventargs e) { base.
Oninitcomplete (e); // the collection to writable
GlobalValues.NameObjectCollectionBaseIsReadOnly.SetValue (Request.querystring, false, null); page.routedata.values.keys.tolist (). ForEach (key => { // add Routedata.values name/value to QueryString collection request.querystring.add (key, Page.RouteData.Values[ Key].
ToString ());
});    &NBSP}}
Then use the code we normally use:
protected void Page_Load (object sender, EventArgs e)
{
//string id = page.routedata.values["id"]. ToString ();
String id = request.querystring["id"];
Response.Write ("
Run it, perfect, aha! OK, add a form form to the ASPX, click on a button a few times to try, finished, the browser address bar address has become:
Http://localhost/Customer/1?Id=1&Id=1&Id=1
The original is, because we each time to querystring add ID this key, the results of each postback is attached to the URL, you have to find ways to delete the page after the end of the querystring from the key, due to the onunload cycle request/ Response has been emptied, so we have to process it in the previous cycle, and the code is as follows:
protected override void Onprerendercomplete (EventArgs e)
{
Page.RouteData.Values.Keys.ToList (). ForEach (Key =>
{
Request.QueryString.Remove (key);
});
Base. Onprerendercomplete (e);
}
Run as usual, OK, perfect, try a few other cases, also no problem.
Note: Because for a long time does not use the Web form to do the project, so I am not sure that the code used in the Oninitcomplete/onprerendercomplete cycle is a reasonable cycle, the current operation is no problem, there is time to study it in detail.
Extend two
Extension one of the code, quite complex, and do not know whether there is no side effects, in fact, the actual project, we generally encapsulate their own getparameter method, so we can use this, relatively simple much:
Namespace easyurl { public abstract class PageBase : System.Web.UI.Page { public string getquerystring (string key, string defaultvalue = "") { if ( Page.RouteData.Values.Keys.Contains (key)) return page.routedata.values[key].
ToString (); else if (String. Isnullorwhitespace (Request.querystring[key])
return Request.QueryString[key]; else return defaultvalue; } public Partial class customer : pagebase { protected void page_load (object sender, eventargs e) { String id = this.
GetQueryString ("id"); response.write ("
Run, no problem, and no more attached on the URL? Id=1 's problem.
asp.net 4.0 seo enhancements urlrouting
1. The usual usage of the URL Routing
Urlrouting is widely used in the ASP.net MVC project, and it works well in MVC, so porting to WebForm, we'll look at how to use it in the WebForm
Suppose a usage scenario: we need to do the page of the blog Daily article, we want the URL address is:
/archive/2010/05/10/default.aspx
This address will be mapped to the ~/posts.aspx file
To use urlrouting, you need to register the urlrouting rules in RouteTable, the code for registering the routing rule in the following global file
Public static void registerroutes (routecollection routes) { routes.
Ignore ("{resource}.axd/{*pathinfo}"); routes. Mappageroute ("Blogs", //a name for this urlrouting rule "archive/{ Year}/{month}/{date}/default.aspx ", //wants friendly URL address format " ~/ Blogs.aspx ", //map to the ASPX page path false, //whether user rights need to be checked new RouteValueDictionary{ { "Year", DATETIME.NOW.YEAR&NBSP}, { "month ", datetime.now.month }, {" Date ", datetime.now.date} },//The default value of the parameter new routevaluedictionary  { {"Year", @ "(19|20) \d{2}"}, {"Month", @ "\d{1,2}"}, {"Date", @ "\d{1,2}"}
} //the rules of the parameter, we limit the date in the URL to the data format we want ); } Void application_start (object sender, eventargs e) { //
Routing Rule registerroutes (routetable.routes) registered at the time of Application_Start; }
2. Use urlrouting parameter values in the page
1 using route values in the background code
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 use on the page
<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:d ate%>" ></asp:Literal>
3) Use of Routeparameter in DataSource
<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 display RouteUrl on the page
<a href= ' <%=getrouteurl ("blogs", new {year=2010,month=05,date=05})%> ' >2010 year May 1 blog </a>
3. The difference between urlrouting and Urlrewrite
urlrouting relative to the URL rewrite is a relatively new thing, Urlrouting's advantage is that can do bidirectional conversion, can do URL rewrite, can also be based on some parameters to get rewritten URL address, but it also has its own deficiencies, such as if you want to even rewrite the domain name, such as blog address yukaizhao.cnblogs.com Such rewriting, urlrouting can not do, can only use Urlrewrite.