The most complete asp.net MVC routing configuration, later Routeconfig can't understand the immortal is difficult to save you ~__.net

Source: Internet
Author: User

Let's talk about basic routing rules. The basic routing rules are from special to general arrangement, that is, the most special (Non-mainstream) rules at the top, the most general (snake) rules in the end. This is because the matching routing rules are also in this order. If the writing is reversed, then even if your routing rules are written right, wait until 404.

XD first says the construction of URLs. In fact, this is also not structure, but the grammatical characteristics of it.


URL Constructs named parameter specification + anonymous object

Routes. Maproute (Name: "Default", url: "{controller}/{action}/{id}", defaults:new {controller = "Home", action = "Index", id = Ur Lparameter.optional});
constructs a route and then adds
Route Myroute = new Route ("{controller}/{action}", New Mvcroutehandler ());
Routes. ADD ("Myroute", Myroute);
Direct method overload + anonymous object
Routes. Maproute ("Shopschema", "Shop/{action}", new {controller = "Home"});

Personally think the first kind of easier to understand, the second convenient debugging, the third write more efficient bar. Get what you have. This paper favors the third kind. Routing Rules 1. Default route (MVC self-band)

Routes. Maproute (
"Default",///Routing name
"{controller}/{action}/{id}",//URL
new {controller with parameters) = "Home", action = "I Ndex ", id = urlparameter.optional}//parameter default value (urlparameter.optional-optional));
2. Static URL segment
Routes. Maproute ("ShopSchema2", "shop/oldaction", new {controller = "Home", action = "Index"});
 
Routes. Maproute ("Shopschema", "Shop/{action}", new {controller = "Home"});
Routes. Maproute ("ShopSchema2", "Shop/oldaction.js",
 new {controller = "Home", action = "Index"});

There is no placeholder route that is ready to write dead.

such as writing and then going to visit Http://localhost:XXX/Shop/OldAction.js,response is completely fine. Controller, action, area these three reserved words are not set static variables inside. 3. Customize the general variable URL segment (all right, this translation exposes IQ)

Routes. Maproute ("MyRoute2", "{Controller}/{action}/{id}", new {controller = "Home", action = "Index", id = "Defaultid"});

In this case, if you access/home/index, because the third paragraph (ID) has no value, this parameter will be set to Defaultid according to the routing rule.

This can be clearly seen by assigning a value to the title with ViewBag.

Viewbag.title = routedata.values["id"];

The picture is not pasted, the result is the caption is displayed as Defaultid. Note To assign values in the controller, the view assignment cannot be compiled. 4. Again, the default route

And then back to the default route. Urlparameter.optional This is called an optional URL segment. The ID is null if this parameter is not in the route. According to the text, this optional URL segment can be used to achieve a separation of concerns. Just set the parameter default value in the route is not very good in fact. As I understand it, the actual parameters are sent by the user, and all we do is define the formal parameter names. However, if you want to assign a default value to a parameter, it is recommended that you write the syntax sugar to the action parameter. Like what:

Public ActionResult Index (string id = "ABCD") {Viewbag.title = routedata.values["id"];return View ();}
5. Variable length routing.
Routes. Maproute ("Myroute", "{Controller}/{action}/{id}/{*catchall}", new {controller = "Home", action = "Index", id = Urlparamet Er. Optional});

Here the ID and the last paragraph are variable, so/HOME/INDEX/DABDAFDAF is equivalent to/home/index//abcdefdjldfiaeahfoeiho equivalent to/home/index/all/delete/perm/ ..... 6. Cross-namespace routing

This reminder remember to reference the namespace, open the IIS Web site or 404. This is very non-mainstream, do not suggest to engage in blind.

Routes. Maproute ("Myroute", "{Controller}/{action}/{id}/{*catchall}", new {controller = "Home", action = "Index", id = Urlparamet Er. Optional},new[] {"Urlsandroutes.additionalcontrollers", "Urlsandroutes.controllers"});

However, the array ranking is not in order, if there are more than one matching route will report an error. Then the author proposes an improved method.

Routes. Maproute ("Addcontollerroute", "Home/{action}/{id}/{*catchall}", new {controller = "Home", action = "Index", id = Urlparameter.optional},new[] {"Urlsandroutes.additionalcontrollers"});
 
Routes. Maproute ("Myroute", "{Controller}/{action}/{id}/{*catchall}", new {controller = "Home", action = "Index", id = Urlparamet Er. Optional},new[] {"Urlsandroutes.controllers"});

So that the first URL segment is not home to the second processing can finally set this route cannot find the next route to leave behind, also no longer down looking.

Route Myroute = routes. Maproute ("Addcontollerroute",
"Home/{action}/{id}/{*catchall}",
new {controller = "Home", action = "Index",  id = urlparameter.optional},
new[] {"Urlsandroutes.additionalcontrollers"}); myroute.datatokens["Usenamespacefallback"] = false;
7. Regular expression-matching routing
Routes. Maproute ("Myroute", "{Controller}/{action}/{id}/{*catchall}",
 new {controller = "Home", action = "Index", id = Urlpa Rameter. Optional},
 new {controller = "^h.*"},
new[] {"Urlsandroutes.controllers"});
constraining multiple URLs
Routes. Maproute ("Myroute", "{Controller}/{action}/{id}/{*catchall}",
new {controller = "Home", action = "Index", id = Urlpa Rameter. Optional},
new {controller = "^h.*", action = "^index$|^about$"},
new[] {"Urlsandroutes.controllers"});
8. Specify the request method
Routes. Maproute ("Myroute", "{Controller}/{action}/{id}/{*catchall}",
 
new {controller = "Home", action = "Index", id = Urlpa Rameter. Optional},
 
new {controller = "^h.*", action = "index| About ", HttpMethod = new Httpmethodconstraint (" Get ")},
 
new[] {" Urlsandroutes.controllers "});
9. WebForm Support
Routes. Mappageroute ("", "", "~/default.aspx");
 
 Routes. Mappageroute ("list", "Items/{action}", "~/items/list.aspx", false, new RouteValueDictionary {{"action", "All"}}); 
  
   routes. Mappageroute ("Show", "Show/{action}", "~/show.aspx", false, new RouteValueDictionary {{"action", "All"}});
 
 Routes. Mappageroute ("edit", "Edit/{id}", "~/edit.aspx", false, new RouteValueDictionary {{"id", "1"}}, New Routevaluedictiona ry {{"id", @ "\d+"}});
  

The concrete can see

Using ASP.NET4 new attribute routing to create WebForm applications

or the official MSDN 10.MVC5 Routeattribute

The first thing to do in the routing registration method

Enables routing attribute mapping
routes. Mapmvcattributeroutes ();

Such

[Route ("Login")]

The route feature is valid. There are several overloads for this feature. There are routing constraints, order, routing names, and so on. Other routing prefixes, routing defaults

[Routeprefix ("Reviews")]<br>[route ("{action=index}")]<br>public class Reviewscontroller:controller <br>{<br>}
Routing Constructs
Eg:/USERS/5
[Route ("Users/{id:int}"] public
actionresult Getuserbyid (int id) {...}
 
Eg:users/ken
[Route ("Users/{name}"] public
actionresult getuserbyname (string name) {...}
parameter Restrictions
Eg:/USERS/5
//But not/users/10000000000 because it is larger than Int. MaxValue,
//and not/users/0 because of the min (1) constraint.
[Route ("Users/{id:int:min (1)}")]
Public ActionResult Getuserbyid (int id) {...}
Constraint Description Example
Alpha Matches uppercase or lowercase Latin alphabet characters (A-Z, A-Z) {X:alpha}
bool Matches a Boolean value. {X:bool}
Datetime Matches a DateTime value. {X:datetime}
Decimal Matches a decimal value. {X:decimal}
Double Matches a 64-bit floating-point value. {x:double}
Float Matches a 32-bit floating-point value. {X:float}
Guid Matches a GUID value. {X:guid}
Int Matches a 32-bit integer value. {X:int}
Length Matches a string with the specified length or within a specified range of lengths. {x:length (6)} {x:length (1,20)}
Long Matches a 64-bit integer value. {X:long}
Max Matches an integer with a maximum value. {X:max (10)}
MaxLength Matches a string with a maximum length. {x:maxlength (10)}
Min Matches an integer with a minimum value. {x:min (10)}
MinLength Matches a string with a minimum length. {x:minlength (10)}
Range Matches an integer within a range of values. {X:range (10,50)}
Regex Matches a regular expression. {X:regex (^\d{3}-\d{3}-\d{4}$)}

Can refer to the specific

Attribute Routing in asp.net MVC 5

For me, the benefit is to spread the definition of routing rules. Some people like to concentrate, I personally prefer this flexible processing. Because this action is defined, I don't need to run to the configuration to define the corresponding route.

Related Article

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.