I. Description of routing rules
Let's look at the description of default routes in MVC
"{Controller}/{action}/{id}// URL with parameters
For URL/HOME/INDEX/1 matching result: Controller: "Home" Action : "Index" Id : "1"
For the ASP. NET MVC framework to function properly, the framework requires some specific parameter names {controller} and {action}.
Let's say we want all the MVC requests to start with the site, so we can change the route.
Site/{controller}/{action}/{id}
If you want all pages to be suffixed with. aspx, you can write this
{Controller}/{action}.aspx/{id}
Now let's copy the Global.asax.cs route and explain
PublicClassMvcApplication:System.Web.HttpApplication {PublicStaticvoidRegisterglobalfilters (globalfiltercollection filters) {filters. ADD (NewHandleerrorattribute ()); }PublicStaticvoidRegisterRoutes (RouteCollection routes) {routes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); Routes. MapRoute ("Default",//The name of the route"{Controller}/{action}/{id}",//Matching rules with parametersNew {controller ="Home", action ="Index", id = urlparameter.optional} // default parameter, that is, when you do not enter a time processing method ); } protected void Application_Start () { //Here can also add a line RouteTable.Routes.RouteExistingFiles = true; //If set to True, this line indicates that all HTTP requests for the site will be compared using the URLs defined in the RegisterRoutes () method, and if the comparison succeeds, it will be handled with ASP. If the comparison fails, check the files on the disk. The default is false, because HTML files, css,js files, etc. can be displayed without prior routing. Arearegistration.registerallareas (); Registerglobalfilters (globalfilters.filters); //Register the route defined earlier, all of the ASP. Mvcrouting are defined here, where the parameter routetable.routes is an exposed static object that stores all the routing ruleset (RouteCollection class) RegisterRoutes (routetable.routes); } }
1, Ignoreroute ignore the route is used to define the routing do not need to deal with the URL.
Example: Http://localhost/Trace.axd
OK, the path matches the success {Resource}.axd to Trace.axd. Instead of {*pathinfo} to null. So the match succeeds. What if the match succeeds? Ignore, not processed. That is, the URL above will not be processed by ASP.
2, MapRoute () most commonly used to define the routing rules of the auxiliary method. Used to define a route. Where the first parameter is the route name, the second parameter is the URL and the parameter, and the third is the default value.
3, we saw a * number before, it represents Catch-all. That is, no matter what the messy things are matched. No match is empty.
4, urlparameter.optional Specifies the default value of optional parameters, when not filled out, will not be added into the parameter dictionary.
Second, custom routing
Routes. MapRoute ("Default",//Route Name"{Controller}/{action}/{id}/{age}/{birthday}",//URL with parametersNew {controller = "home", action = "index", id =18, Birthday=new DateTime ( 1989,1,1)}, //); public actionresult Index (string ID, int age, DateTime birthday) {return View ();}
If we define a pattern with the three parameters defined in the route and then enter the correct URL, the routing system will automatically extract the controller, the action, and the three parameters (if the parameter name matches, and the type conversion can be completed). For example, when we enter Http://localhost/User/Getinfo/123344/24/1989-9-16, the route extracts the information, controller=user, action = getinfo,id=123344, Age=24, birthday=1989-9-16Iii. routing for defining variable-length parameters
routes. MapRoute ( "default", Span style= "color: #008000;" >// route name {controller} /{action}/{id}/{*catchall}// new {controller = "homeindex "//
This route can match all the URLs. Specific matching conditions such as:
Serial number |
URL Example |
Mapping results |
0 |
mydomain.com |
Controller=home,action=index |
1 |
Mydomain.com/customer |
Controller=customer,action=index |
2 |
Mydomain.com/customer/list |
Controller=customer,action=list |
3 |
Mydomain.com/customer/list/all |
Controller=customer,action=list,id=all |
4 |
Mydomain.com/customer/list/all/delete |
Controller=customer,action=list,id=all,catchall=delete |
5 |
Mydomain.com/customer/list/all/delete/perm |
Controller=customer,action=list,id=all,catchall=delete/perm |
Four. Define the priority of the namespace
As we know from the above, when the URL matches the previous route, the information in the route is extracted and then processed further. If one of our routes now extracts a controller for account, and there is more than one class named "AccountController" in our solution, there will be an error at this time because the route does not know which controller to invoke. So, how to solve this problem? When registering a route, we can specify a namespace for which a route is limited to find the controller, as shown in the following code.
Routes. MapRoute ("Default",//Route Name "{controller}/{action}/{id} ", // URL with parameters new {controller = "home index "//new string["{mynamespace.controllers "} // Specify a priority namespace);
v. Routing constraints /c0>We can add the following restrictions to the URL match: A, regular expression B,http method
Routes. MapRoute ("Default",//Route Name"{Controller}/{action}/{id}",//URL with parametersNew{controller ="Home", action ="Index "//// set matching constraints Span style= "color: #0000ff;" >new {controller = "^h.* ^index$|^ About& " // The route must be successfully matched by a regular expression to use the Httpmethod=new Httpmethodconstrain ( "get" //specifies that only requests using the GET method will be matched);
This route requires that the controller must have a value that begins with the letter "H", and that the action can only be index or about, and can only be used in get mode. If these system-defined constraints do not meet the requirements of the project, we can customize the constraints, as long as the Irouteconstraint interface is implemented, and then one instance of the class is passed to routs. The code is as follows:
PublicClassuserconstrain:irouteconstraint{PublicboolMatch (HttpContextBase HttpContext, Route route,StringParameterName, routevaluedictionary values, Routedirection routedirection) {Returntrue;//You can do a specific operation here.}} routes. MapRoute ("Default",//Route Name"{Controller}/{action}/{id}",//URL with parametersNew {controller ="Home", action ="Index", ID =urlparameter.optional},//Parameter Default valueNew {controller ="^h.*", action ="^index$|^about&" , httpmethod=new Httpmethodconstrain ("Get "), customconstrain= new Userconstrain ()}, // set match constraint new string[] { "MyName Space. Controllers"} // Specify priority namespace);
MVC Routing Rules