Note: This article is not about the MVC framework.
ASP. NET 3.5 SP1 provides a routing technology. ASP. NET routing is a technology that enables us to use descriptive and user-friendly URLs to access resources in ASP. NET applications. Such URLs do not need to be physically mapped to real resources. For example:
Http://dotnet.aspx.cc/Article.aspx? ArticleID = 8d01fd5e-b2c1-40f5-8cea-bc2197fb9bd8
This URL is actually mapped to an article. aspx file under the root directory of the website. Using ASP. NET routing technology, you can use a URL similar to the following:
Http://dotnet.aspx.cc/article/8d01fd5e-b2c1-40f5-8cea-bc2197fb9bd8/read.aspx
There are two technologies to implement this URL: URL rewriting and URL routing:
1. URL rewriting processes incoming requests by actually changing the URL before sending the request to the webpage. For example, an application that uses URL rewriting may
/Article/8d01fd5e-b2c1-40f5-8cea-bc2197fb9bd8/read. aspx changed
/Article. aspx? ArticleID = 8d01fd5e-b2c1-40f5-8cea-bc2197fb9bd8. In addition
There is usually no corresponding API to create a pattern-based URL for rewriting. In URL rewriting, if the URL mode is changed, you must manually update the file containing the original URL.
.
2. Because ASP. NET routes can extract values from URLs, the URL is not changed when processing incoming requests. If you must create a URL, pass the parameter value to
URL method. To change the URL mode, change the mode at a certain location. All links created in the application based on this mode will automatically use the new mode.
To enable routing, you must modify the application configuration file to register the routing assembly and add the urlroutingmodule
Class as a module. You must also create a custom route handler for the route. This handler implements the iroutehandler interface and creates a web form (. aspx
File), the instance is the actual end point of the request.
The following is a complete example to illustrate how to use this technology in the website publishing system.
1. First, create a table article to store the content of the article data, and create an SQL statement from SQL Server 2000 Script Creation function:
Reate table [Article] (<br/> [ArticleID] [int] identity (1, 1) not null, <br/> [title] [nvarchar] (255) collate chinese_prc_ci_as not null, <br/> [createdate] [datetime] not null constraint [df_article_createdate] default (getdate ()), <br/> [content] [ntext] collate chinese_prc_ci_as not null, <br/> constraint [pk_article] primary key clustered <br/> (<br/> [ArticleID] <br/>) on [primary] <br/>) on [primary] textimage_on [primary] <br/> go <br/>
2. In vs2008sp1 or vs2010, create an ASP. NET Website and add a reference to system. Web. routing;
3. Create a custom route handler and add a new "class" in the website project. Name it articleroutehandler. cs. The website content of the class is as follows:
Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. web; <br/> using system. web. ui; <br/> using system. web. routing; <br/> using system. web. compilation; <br/> /// <summary> <br/> // Summary of articleroutehandler <br/> /// </Summary> <br/> public class articleroutehandler: iroutehandler <br/>{< br/> Public articleroutehandler () <br/>{< br/> // <br/> // todo: Add constructor here Logic <br/> // <br/>}< br/> Public ihttphandler gethttphandler (requestcontext) <br/>{< br/> string articleguid = requestcontext. routedata. values ["articleguid"] as string; <br/> httpcontext context = httpcontext. current; <br/> context. items. add ("articleguid", articleguid); <br/> string action = (requestcontext. routedata. values ["action"] as string ). tolower (); <br/> If (action. equals ("R EAD ") <br/> return buildmanager. createinstancefromvirtualpath ("~ /Articleshow. aspx ", typeof (page) as page; <br/> else if (action. equals ("new") <br/> return buildmanager. createinstancefromvirtualpath ("~ /Articleadd. aspx ", typeof (page) as page; <br/> else if (action. equals ("edit") <br/> return buildmanager. createinstancefromvirtualpath ("~ /Articleedit. aspx ", typeof (page) as page; <br/> else if (action. equals ("comment") <br/> return buildmanager. createinstancefromvirtualpath ("~ /Articlecomment. aspx ", typeof (page) as page; <br/> else if (action. equals ("print") <br/> return buildmanager. createinstancefromvirtualpath ("~ /Articleprint. aspx ", typeof (page) as page; <br/> else <br/> return buildmanager. createinstancefromvirtualpath ("~ /Articlelist. aspx ", typeof (page) as page; <br/>}< br/>}
Note:
Using system. Web. UI;
Using system. Web. Routing;
Using system. Web. compilation;
These three lines of code are newly added.
Here, we place the placeholder parameter in the URL address in the httpcontext. Current object to obtain it on the real processing page and then perform the corresponding operations. The key code is the following:
String articleguid = requestcontext. routedata. Values ["articleguid"] as string;
Httpcontext context = httpcontext. Current;
Context. Items. Add ("articleguid", articleguid );
4. Register a route in global with the code:
<% @ Application language = "C #" %> <br/> <% @ import namespace = "system. web. routing "%> <br/> <MCE: script runat =" server "> <! -- <Br/> void application_start (Object sender, eventargs e) <br/>{< br/> registerroutes (routetable. routes); <br/>}< br/> Public static void registerroutes (routecollection routes) <br/>{< br/> routes. add ("articleroute", new route <br/> (<br/> "Article/{articleguid}/{action }. aspx ", <br/> New articleroutehandler () <br/> ); <br/>}</P> <p> // --> </MCE: SCRIPT>
Here, as an example, only one URL rule is defined, article/{articleguid}/{action}. aspx.
5. Add articleshow. aspx, articleadd. aspx, and,
Articleedit. aspx, articlecomment. aspx, articleprint. aspx, and articlelist. aspx
Real handler.
For example, the source codes of articleshow. aspx, articleadd. aspx, and articlelist. aspx are listed as follows:
Articleadd. aspx
<% @ Page Language = "C #" validaterequest = "false" %> <br/> <% @ import namespace = "system. data "%> <br/> <% @ import namespace =" system. data. sqlclient "%> <br/> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <br/> <MCE: script runat = "server"> <! -- <Br/> protected void button1_click (Object sender, eventargs e) <br/>{< br/> string connectionstring = "Data Source = (local); initial catalog = articledev; user ID = sa; Password = sa "; <br/> sqlconnection Cn = new sqlconnection (connectionstring); <br/> CN. open (); <br/> string SQL = "insert into article (title, content) values (@ title, @ content )"; <br/> sqlcommand cmd = new sqlcommand (SQL, CN); <br/> cmd. para Meters. addwithvalue ("@ title", textbox1.text); <br/> cmd. parameters. addwithvalue ("@ content", textbox2.text); <br/> int ret = cmd. executenonquery (); <br/> If (ret = 1) <br/>{< br/> label1.text = "added successfully. "; <Br/>}< br/> else <br/>{< br/> label1.text =" adding failed. "; <Br/>}< br/> CN. dispose (); <br/>}< br/> // --> </MCE: SCRIPT> <br/> <HTML xmlns = "http://www.w3.org/1999/xhtml"> <br/> <pead runat = "server"> <br/> <title> </title> <br/> </pead> <br/> <body> <br/> <Form ID = "form1" runat = "server"> <br/> <div> Article Title: <asp: textbox id = "textbox1" runat = "server" width = "767px"> </ASP: textbox> </div> <br/> <div> content: <br/> <asp: textbox id = "textbox2" runat = "server" width = "845px" Height = "319px" textmode = "multiline"> <br/> </ASP: textbox> </div> <br/> <asp: button id = "button1" runat = "server" text = "add article" onclick = "button#click"/> <br/> <asp: label id = "label1" runat = "server" text = ""> </ASP: label> <br/> </form> <br/> </body> <br/> </ptml>
Articleshow. aspx
<% @ Page Language = "C #" %> <br/> <% @ import namespace = "system. data "%> <br/> <% @ import namespace =" system. data. sqlclient "%> <br/> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <br/> <MCE: script runat = "server"> <! -- <Br/> protected void page_load (Object sender, eventargs e) <br/>{< br/> int articleguid = 0; <br/> httpcontext context = httpcontext. current; <br/> If (context. items ["articleguid"]! = NULL) <br/>{< br/> int32.tryparse (context. items ["articleguid"]. tostring (), Out articleguid); <br/>}< br/> If (articleguid <1) <br/>{< br/> articletitle. innerhtml = "loading document error"; <br/> articlecontent. innerhtml = "the specified identifier is invalid! "; <Br/> articlecontent. style ["color"] = "# f00 "; <br/>}< br/> else <br/> {<br/> string connectionstring = "Data Source = (local); initial catalog = articledev; user id = sa; password = sa "; <br/> sqlconnection Cn = new sqlconnection (connectionstring); <br/> CN. open (); <br/> string SQL = "select * from article where ArticleID = @ ArticleID"; <br/> sqlcommand cmd = new sqlcommand (SQL, CN ); <br/> cmd. parameters. Addwithvalue ("@ ArticleID", articleguid); <br/> sqldatareader DR = cmd. executereader (); <br/> If (dr. read () <br/>{< br/> articletitle. innerhtml = Dr ["title"]. tostring (); <br/> articlecontent. innerhtml = Dr ["content"]. tostring (); <br/>}< br/> else <br/>{< br/> articletitle. innerhtml = "loading document error"; <br/> articlecontent. innerhtml = "the specified article does not exist! "; <Br/> articlecontent. style ["color"] = "# f00"; <br/>}< br/> CN. dispose (); <br/>}< br/> // --> </MCE: SCRIPT> <br/> <HTML xmlns = "http://www.w3.org/1999/xhtml"> <br/> <pead runat = "server"> <br/> <title> </title> <br/> </pead> <br/> <body> <br/> <Form ID = "form1" runat = "server"> <br/> <H2 id = "articletitle" runat = "server" style = "text-align: center "mce_style =" text-align: center "> <br/> </H2> <br/> <HR/> <br/> <Div id =" articlecontent "runat =" server "> <br/> </div> <br/> </form> <br/> </body> <br/> </ptml>
In this Code, we retrieve the context. items ["articleguid"] parameter from the httpcontext object added in the Custom route processing program, and then process it.
Articlelist. aspx
<% @ Page Language = "C #" %> <br/> <% @ import namespace = "system. data "%> <br/> <% @ import namespace =" system. data. sqlclient "%> <br/> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <br/> <MCE: script runat = "server"> <! -- <Br/> protected void page_load (Object sender, eventargs e) <br/>{< br/> string connectionstring = "Data Source = (local); initial catalog = articledev; user ID = sa; Password = sa "; <br/> sqlconnection Cn = new sqlconnection (connectionstring); <br/> CN. open (); <br/> string SQL = "select * from article order by ArticleID DESC"; <br/> sqlcommand cmd = new sqlcommand (SQL, CN ); <br/> sqldatareader DR = cmd. ex Ecutereader (); <br/> gridview1.datasource = Dr; <br/> gridview1.databind (); <br/> CN. dispose (); <br/>}< br/> // --> </MCE: SCRIPT> <br/> <HTML xmlns = "http://www.w3.org/1999/xhtml"> <br/> <pead runat = "server"> <br/> <title> </title> <br/> </pead> <br/> <body> <br/> <Form ID = "form1" runat = "server"> <br/> <asp: gridview id = "gridview1" runat = "server" autogeneratecolumns = "false"> <br/> <columns> <br/> <asp: Hyp Erlinkfield datanavigateurlfields = "ArticleID" datatextfield = "title" <br/> datanavigateurlformatstring = "~ /Article/{0}/read. aspx "headertext =" title "/> <br/> <asp: boundfield datafield = "createdate" htmlencode = "false" headertext = "Release Date" <br/> dataformatstring = "{0: yyyy-mm-dd hh: mm: SS} "/> <br/> </columns> <br/> </ASP: gridview> <br/> </form> <br/> </body> <br/> </ptml>
6. If the ASP. NET version set in IIS is ASP. NET 4.0, you do not need to configure the following configuration. If it is ASP. NET 2.0, You need to configure the route in Web. config.
In the Web. config file of the application, add the ASP. NET route assembly to the assemblies element.
<Assemblies> <br/> <add Assembly = "system. Web. Routing, version = 3.5.0.0, culture = neutral, publickeytoken = 31bf3856ad364e35"/> <br/> </assemblies>
If the application runs in the IIS 6.0 or IIS 7.0 classic model, add the urlroutingmodule class to the httpmodules element.
<Httpmodules> <br/> <Add name = "urlroutingmodule" <br/> type = "system. web. routing. urlroutingmodule, <br/> system. web. routing, <br/> Version = 3.5.0.0, <br/> Culture = neutral, <br/> publickeytoken = 31bf3856ad364e35 "/> <br/> </pttpmodules>
The following address can be used for access. Of course, this is just an example. More functions need to be processed in practice.
Http://dotnet.aspx.cc/article/8d01fd5e-b2c1-40f5-8cea-bc2197fb9bd8/comment.aspx
Http://dotnet.aspx.cc/article/8d01fd5e-b2c1-40f5-8cea-bc2197fb9bd8/new.aspx
Http://dotnet.aspx.cc/article/8d01fd5e-b2c1-40f5-8cea-bc2197fb9bd8/edit.aspx
Http://dotnet.aspx.cc/article/8d01fd5e-b2c1-40f5-8cea-bc2197fb9bd8/read.aspx
Http://dotnet.aspx.cc/article/8d01fd5e-b2c1-40f5-8cea-bc2197fb9bd8/print.aspx
The above example is a simple description. in actual application, there are more things to consider. For more information, refer to the following link:
ASP. NET routing (http://msdn.microsoft.com/zh-cn/library/cc668201.aspx)