MVC Routing Rules

Source: Internet
Author: User
Tags url example

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 Url/a.b/c-d/e-f
The matching results are:
Controller: "A.B"
Action: "C-d"
Id: "E-f"

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

public class MvcApplication:System.Web.HttpApplication {public static void Registerglobalfilters (Globalfilter Collection filters) {filters.        ADD (New Handleerrorattribute ()); public static void RegisterRoutes (RouteCollection routes) {routes.            Ignoreroute ("{resource}.axd/{*pathinfo}"); Routes.  MapRoute ("Default",//route name "{controller}/{action}/{id}",//matching rule with parameters new {        Controller = "Home", action = "Index", id = urlparameter.optional}//default parameter, that is, when the time is not entered processing method); } protected void Application_Start () {
You can also add a row here
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);
Registers the previously defined route, where all ASP. Mvcrouting is defined, where the parameter routetable.routes is an exposed static object that stores all routing rule sets (RouteCollection Class) Regis Terroutes (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.

Ii. Custom Routing
Routes. MapRoute (    "Default",//route name    "{controller}/{action}/{id}/{age}/{birthday}",//URL with parameter    new {controller = "Home", action = "Index", id = urlparameter.optional,              age=18, Birthday=new DateTime (1989,1,1)},//parameter default value    );p UB Lic 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-16. Routing for defining variable-length parameters
Routes. MapRoute (    "Default",///route name    "{Controller}/{action}/{id}/{*catchall}",//URL with variable number of parameters    new { Controller = "Home", action = "Index",        id=urlparameter.optional     },//parameter default value);
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 parameter    new {controller = "Home", action = "I Ndex ",     id = urlparameter.optional},//parameter default value    new string[] {" Mynamespace.controllers "}//Specify priority namespace);
V. Routing constraints we can add the following restrictions to URL matches: A, regular expression B,http method
  Routes. MapRoute (    "Default",//route name    "{controller}/{action}/{id}",//URL with parameter    new {         controller = "Home",        action = "Index",        id = urlparameter.optional},//parameter default value        //Set match constraint    new  {controller = "^h.*", action = "^index$|^about&",//must be successfully matched by a regular expression before using the route        httpmethod=new httpmethodconstrain ("Get")}//Specifies that only requests using the Get method will be matching);
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:
public class userconstrain:irouteconstraint{Public    bool Match (HttpContextBase HttpContext, Route route,     String  parametername,  routevaluedictionary values,    routedirection routedirection)    {    return true; You can do a specific operation here    }}        routes.  MapRoute (    "Default",//route name    "{controller}/{action}/{id}",//URL with parameter    new {controller = "Home", action = "Index", id         =urlparameter.optional},//parameter default value    new  {controller = "^h.*", action = "^index$|^about&",             httpmethod=new httpmethodconstrain ("Get"),    customconstrain= new  Userconstrain ()},//Set match constraint    New string[] {"Mynamespace.controllers"}  //Specify priority namespace);

MVC Routing Rules

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.