In this tutorial, you will learn how to apply ASP. NET MVCProgramAdd a custom route. You will learn howChange the default route table in the global. asax file to a custom route.
For simple ASP. net mvc applications, the default route table can be well completed. However, you may find that there are specific routing requirements. In this case, you can create a custom route.
Imagine, for example, you are creating a blog application. You may want to process the coming request like this:
/Lingling/10-28-1987
When you enter this request, you want to return the blog entry corresponding to the date 10/28/1987. To process such requests, you need to create a custom route.
BelowCodeGlobal. asax in contains a new custom Route named blog, which processes requests such as/Lingling/entry date.
Using System. Web. MVC; Using System. Web. Routing; Namespace Mvcapplication1 { Public Class Mvcapplication: system. Web. httpapplication { Public Static Void Registerroutes (routecollection routes) {routes. ignoreroute (" {Resource}. axd/{* pathinfo} "); Routes. maproute (" Blog ", // Route name " Lingling/{entrydate} ", // URL with Parameters New {Controller ="Lingling ", Action =" Entry "} // Parameter defaults ); Routes. maproute (" Default ", // Route name " {Controller}/{action}/{ID} ", // URL with Parameters New {Controller =" Home ", Action =" Index ", Id =" "} // Parameter defaults );} Protected Void Application_start () {registerroutes (routetable. routes );}}}
The route order added to the route table is very important. Our new custom blog route is placed before the existing default route. If you turn this order upside down, the default route will always be called, rather than a custom route.
Custom blog routes match any requests starting with/archive. Therefore, it matches all the following urls:
/Lingling/12-25-2009
/Lingling/10-6-2004
/Lingling/Apple
Custom routing maps incoming requests to the Controller named archive and calls the entry () action. When the entry () method is called, the entry date is passed as the entrydate parameter.
UsingSystem;UsingSystem. Web. MVC;NamespaceMvcapplication1.controllers {Public ClassArchivecontroller: controller {Public StringEntry (datetime entrydate ){Return"You requested the entry from"+ Entrydate. tostring ();}}}
Note that the entry () method in the Code accepts a datetime type parameter. The MVC framework is very clever enough to automatically convert the entry date in the URL to the datetime value. If the entry date parameter in the URL cannot be converted to datetime, an error is thrown.