The most complete ASP. NET MVC routing configuration in history

Source: Internet
Author: User
Let's start with the basic routing rules principle. The basic routing rules are from special to general arrangement, that is, the most special (non-mainstream) rules at the top, the most general (balm) rules at the end. This is because the matching routing rules are also in this order. If the write is reversed, then even if your routing rules are right, then wait for 404.

XD first says the construction of the URL. In fact, this is not the construction, 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});

Construct the route and add

Route Myroute = new Route ("{controller}/{action}", New Mvcroutehandler ()); routes. ADD ("Myroute", Myroute);

Direct method overloading + anonymous objects

Routes. MapRoute ("Shopschema", "Shop/{action}", new {controller = "Home"});

Personally feel that the first kind of easier to understand, the second convenient debugging, the third kind of writing more efficient bar. Picking it. This article is biased towards the third type.

Routing rules

1. Default route (MVC comes with)

Routes. MapRoute ("Default",//route name "{controller}/{action}/{id}",//Urlnew with parameter {controller = "Home", action = "Index", id = Url Parameter.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"});

No placeholder routing is ready to write dead.

For example, it is absolutely no problem to write and visit http://localhost:XXX/Shop/OldAction.js,response. Controller, action, area these three reserved words do not set static variables inside.

3. Custom regular variable URL segment (well this translates exposure 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 in ViewBag.

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

The picture is not affixed, the result is that the title is displayed as Defaultid. Note that to assign values to the controller, the view assignment cannot be compiled.

4. Re-stating the default route

Then go back to the default route. Urlparameter.optional This is called an optional URL segment. The ID is null if the parameter is not in the route. Roughly speaking, this optional URL segment can be used to achieve a separation of concerns. Just setting the default value of the parameter directly in the route is not really good. According to my understanding, the actual parameters are sent by the user, we only do the definition of formal parameter names. However, if you want to assign a default value to a parameter, it is recommended that you write the syntax sugar into 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});

Both the ID and the last paragraph are mutable here, so/home/index/dabdafdaf is equivalent to/home/index//abcdefdjldfiaeahfoeiho equivalent to/home/index/all/delete/perm/ .....

6. Cross-namespace routing

This reminds you to remember to refer to the namespace, open the IIS Web site, or 404. This is very non-mainstream, it is not recommended 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 is ranked in no particular order, if there are multiple matching routes will be error. Then the author proposes an improved writing 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 the first URL segment is not home to the second processing finally can also set the route cannot find the words will not give back the route left behind, it will no longer look down.

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 route

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

Constrain multiple URLs

Routes. MapRoute ("Myroute", "{Controller}/{action}/{id}/{*catchall}", new {controller = "Home", action = "Index", id = Urlparamet Er. 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 = Urlparamet Er. 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

Creating WebForm Apps with asp.net4 new feature routing

or the official MSDN

10.MVC5 's Routeattribute

The first thing to do in the route registration method there

Enable routing attribute mapping routes. Mapmvcattributeroutes ();

Such

[Route ("Login")]

The route attribute is valid. There are several overloads for this attribute. and routing constraints Ah, order Ah, route name and so on.

The other is the route prefix, the route default value

[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/{nam e} "]public ActionResult getuserbyname (string name) {...}

Parameter limits

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}$)}

The specific can be referenced

Attribute Routing in ASP. NET MVC 5

The advantage for me is that it distracts from the definition of routing rules. Some people like to concentrate, I personally prefer this kind of flexible processing. Since this action is defined, I don't need to run to the configuration there to define the corresponding routing rules

11. Finally, I write a class to implement Irouteconstraint matching method.

using system;using system.collections.generic;using system.linq;using System.Web;using system.web.routing;///<summary>///If The standard constraints is not sufficient for your needs, can define Yo ur own custom constraints by implementing the Irouteconstraint interface.///</summary>public class Useragentconstr    aint:irouteconstraint{private String requireduseragent;    Public Useragentconstraint (String agentparam) {requireduseragent = Agentparam; } public bool Match (HttpContextBase HttpContext, Route route, String parametername, routevaluedictionary values, Rou Tedirection routedirection) {return httpContext.Request.UserAgent! = null && httpcontext.request .    Useragent.contains (requireduseragent); }}
Routes. MapRoute ("Chromeroute", "{*catchall}", new {controller = "Home", action = "Index"}, new {customconstraint = new userage Ntconstraint ("Chrome")}, new[] {"Urlsandroutes.additionalcontrollers"});

For example, this is used to match whether the Web page is accessed using Google Chrome.

12. Accessing Local documents

Routes. Routeexistingfiles = true; Routes. MapRoute ("Diskfile", "content/staticcontent.html", new {controller = "Customer", action = "List",});

Browse the site to open IIS Express, then click Show All Apps-click Site name-Configure (applicationhost.config)-Search UrlRoutingModule node

<add name= "UrlRoutingModule-4.0" type= "System.Web.Routing.UrlRoutingModule" precondition= "Managedhandler, runtimeVersionv4.0 "/>

Delete the precondition in this node and turn it into

<add name= "UrlRoutingModule-4.0" type= "System.Web.Routing.UrlRoutingModule" precondition= "/>

13. Direct access to local resources, bypassing the routing system

Routes. Ignoreroute ("content/{filename}.html");

The file name can also be used with the {filename} placeholder.

The Ignoreroute method is an instance of the Stoproutinghandler class inside the routecollection. The routing system recognizes this handler by hard-coding. If this rule matches, the subsequent rules are invalid. This is also the default route inside the routes. Ignoreroute ("{resource}.axd/{*pathinfo}"); write the most previous reason.

Routing test (on the basis of the test project, to install MOQ)

Pm> Install-package Moq
Using system;using microsoft.visualstudio.testtools.unittesting;using system.web;using Moq;using System.Web.Routing ; using System.Reflection; [Testclass]public class routestest{Private HttpContextBase createhttpcontext (string targeturl = null, String Httpmetho D = "GET") {//Create the mock request mock

Finally, I would recommend Adam Freeman to write apress.pro.asp.net.mvc.4 the book. A little familiarity with MVC begins with the second part of reading. The front is all about getting started (for me it's nonsense). But it's better than some people who write books in China--Download the source code of an open source project to the top of the book, then the title of a deep analysis of XXXX, and then the net nonsense light. The last 1000 multi-page masterpiece was born again. Adam Freeman Style I like, are examples of writing, and then there is a book in there specifically written a lot of tests.

Hey no way, the technology gap is like this.

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.