ASP. Mvc]asp.net MVC5 Series--routing Features

Source: Internet
Author: User

Directory

Overview

Routing characteristics

Using routing

Default values for optional parameters and parameters

Route prefixes

Default route

Routing constraints

Custom Routing constraints

Route Name

Zone (area)

Summarize

Series Articles

[ASP. NET MVC] ASP. MVC5 Series--First project

[ASP. NET MVC] ASP. MVC5 Series--Add view

[ASP. NET MVC] ASP. MVC5 Series--Add model

[ASP. NET MVC] ASP. MVC5 Series--accessing data from the controller in the model

[ASP. NET MVC] ASP. MVC5 Series--Add data

[ASP. NET MVC] ASP. MVC5 Series--Adding validation rules to the model

[ASP. NET MVC] ASP. MVC5 Series--Edit, delete and detail view

[ASP. NET MVC] ASP. NET MVC5 series--razor syntax

Overview

ASP. NET MVC 5 supports a new routing protocol called routing characteristics. As the name implies, routing attributes use attributes to define paths. The routing feature gives you more control over the URI of your Web application. Of course, MVC5 also supports the way in which routes were previously defined, and you can use these two methods to define routes in a single project.

Routing characteristics

For example, an e-commerce site might have the following routing rules:

{Productid:int}/{producttitle} Mapped to productscontroller.show (int id) {username} Mapped to Profilescontroller.show ( String username) {Username}/catalogs/{catalogid:int}/{catalogtitle} Mapped to Catalogscontroller.show (string Username, int catalogid)

In the previous ASP. NET MVC version, the rule will be set in the Routeconfig.cs file and indicate the actual controller's action method, such as:

1 routes. MapRoute (2     Name: "Productpage", 3     URL: "{productid}/{producttitle}", 4     defaults:new {controller = " Products ", action =" Show "},5     constraints:new {productId =" \\d+ "}6);

When the definition of a route is declared in the same source file as the action method, rather than in the external configuration class, it is easier to handle the mapping between the URI and the action. The previous path definition will use the following, simple features to achieve the purpose:

1 [Route ("{productid:int}/{producttitle}")]2 public actionresult Show (int productId) {...}
Using routing Attributes

To enable attribute routing first, we can call the Mapmvcattributeroutes method to enable attribute routing:

1 public class RouteConfig2 {3 public     static void RegisterRoutes (RouteCollection routes) 4     {5         routes. Ignoreroute ("{resource}.axd/{*pathinfo}"); 6  7         routes. Mapmvcattributeroutes (); 8     }9}

It can also be used in conjunction with regular routing settings.

1 public static void RegisterRoutes (RouteCollection routes) 2 {3     routes. Ignoreroute ("{resource}.axd/{*pathinfo}"); 4   5     routes. Mapmvcattributeroutes (); 6   7     routes. MapRoute (8         Name: "Default", 9         URL: "{controller}/{action}/{id}",         defaults:new {controller = "Home", Action = "Index", id = urlparameter.optional}11     ); 12}
default values for optional URI parameters and Parameters

Can be added by adding "?" Mark a parameter as an optional parameter, or set a default value for the form parameter (parameter =value).

1 public class Bookscontroller:controller 2 {3     //Eg:/books 4     //Eg:/books/1430210079 5     [Route ("Books/{is BN} ")] 6 Public     ActionResult View (String ISBN) 7     {8         if (! String.IsNullOrEmpty (ISBN)) 9         {Ten             return view ("Onebook", GetBook (ISBN)),         }12         return View (" Allbooks ", Getbooks ());     }14     //eg:/books/lang16     //eg:/books/lang/en17     //eg:/books/ Lang/he18     [Route ("books/lang/{lang=en}")]19 public     actionresult viewbylanguage (string lang)     {21         return View ("Onebook", Getbooksbylanguage (Lang));     23}

In the example above,/books and/books/1430210079 will be routed to the view method, which will return the list information for all books, which will return information for a particular book. /books/lang and/books/lang/en will take the same approach.

Route prefixes

Within the same controller, the route starts with the same prefix, for example:

1 public class Reviewscontroller:controller 2 {3     //Eg:/reviews 4     [Route ("Reviews")] 5 public     ActionResult Index () {...} 6     //Eg:/REVIEWS/5 7     [Route ("Reviews/{reviewid}")] 8 public     actionresult Show (int reviewid) { ... } 9     //eg:/reviews/5/edit10     [Route ("Reviews/{reviewid}/edit")]11 public     actionresult edit (int reviewid) { ... } 12}

You can set a common prefix for the entire controller by using the [Routeprefix] feature:

1 [Routeprefix ("Reviews")] 2 public class Reviewscontroller:controller 3 {4     //EG.:/reviews 5     [Route] 6
   
    public ActionResult Index () {...} 7     //EG.:/REVIEWS/5 8     [Route ("{Reviewid}")] 9 public     ActionResult Sho W (int reviewid) {...}     //eg.:/reviews/5/edit11     [Route ("{reviewid}/edit")]12 public     actionresult edit (int reviewid) {... }13}
   

If you need to define a different route prefix, you can overwrite the original prefix with a tilde ~ on the method attribute, for example:

1 [Routeprefix ("reviews")]2 public class Reviewscontroller:controller3 {4     ///EG.:/spotlight-review5     [Route (" ~/spotlight-review ")]6 public     ActionResult showspotlight () {...} 7  8     ... 9}
default route

You can also use the [path] attribute at the controller level to take the action method as a parameter. The route will be applied to all action methods in the Controller, unless the action method uses a specific [routing] attribute, otherwise the controller-level default route will be used.

1 [Routeprefix ("Promotions")] 2 [Route ("{action=index}")] 3 public class Reviewscontroller:controller 4 {5     //EG.: /promotions 6 Public     ActionResult Index () {...} 7   8     //EG.:/promotions/archive 9 public     ActionResult Ar Chive () {...}     $//eg.:/promotions/new12 public     ActionResult New () {...}     //eg.:/promotions/edit/515     [Route ("Edit/{promoid:int}")]16 public     actionresult edit (int promoid) {...} 17}

As we know, the priority of the action method's routing attribute is greater than the priority of the controller routing attribute.

Routing Constraints

Routing constraints allow you to limit how parameters in the routing template match, and the general syntax is {parameter:constraint}, for example:

1//eg:/USERS/52 [Route ("Users/{id:int}"]3 public actionresult Getuserbyid (int id) {...} 4  5//EG:USERS/KEN6 [Route ("Users/{name}"]7 Public actionresult Getuserbyname (string name) {...}

Here, if the ID is of type int, the first route is selected, otherwise the second route is selected.

The following table lists the supported constraints:

Note that some of the constraints with Min are available with parameters.

You can also apply multiple constraints on one parameter, multiple constraints with semicolons ";" Split, for example:

1//EG:/USERS/52//But not/users/10000000000 because it is larger than Int. maxvalue,3//And not/users/0 because of the min (1) constraint.4 [Route ("Users/{id:int:min (1)}")]5 public ActionResult Ge Tuserbyid (int id) {...}

Through the question mark "?" Optional parameters can be specified in an inline constraint, for example:

1//EG:/greetings/bye2//And/greetings because of the Optional modifier,3//But Not/greetings/see-you-tomorrow Becau SE of the MaxLength (3) constraint.4 [Route ("Greetings/{message:maxlength (3)}")] 5 Public ActionResult Greet (String message) {...}
Custom Routing Constraints

You can customize the IRouteConstraint routing constraints by implementing an interface, for example, defining a constraint on the validity of a parameter:

1 public class Valuesconstraint:irouteconstraint 2 {3     private readonly string[] validoptions, 4 public     Valuesco Nstraint (String options) 5     {6         validoptions = options. Split (' | '); 7     } 8   9 public     bool Match (HttpContextBase HttpContext, Route route, String ParameterName, RouteValueDictionary values, routedirection routedirection)     {One         object value;12         if (values). TryGetValue (parametername, out value) && value! = null)         -{             validoptions.contains (value) ToString (), stringcomparer.ordinalignorecase);         }16         return false;17     }18}

Then you register the custom constraint:

1 public class Routeconfig 2 {3 public     static void RegisterRoutes (RouteCollection routes) 4     {5         routes. Ignoreroute ("{resource}.axd/{*pathinfo}"); 6   7         var constraintsresolver = new Defaultinlineconstraintresolver (); 8   9         CONSTRAINTSRESOLVER.CONSTRAINTMAP.ADD ("Values", typeof (Valuesconstraint));         routes. Mapmvcattributeroutes (constraintsresolver);     }13}

Now you can use the custom constraint in your route.

1 public class Temperaturecontroller:controller2 {3     //Eg:temp/celsius And/temp/fahrenheit but not/temp/kelvin4< C13/>[route ("Temp/{scale:values (Celsius|fahrenheit)}")]5 public     actionresult Show (String scale) 6     {7         return Content ("scale was" + scale); 8     } 9}
Route name

You can specify a name for a route in order to generate the appropriate URL. For example:

1 [Route ("menu", Name = "MainMenu")]2 public ActionResult MainMenu () {...}

You can use Url.routeurl to generate the appropriate URL

1 <a href= "@Url. ROUTEURL (" MainMenu ")" >main menu</a>
Zone (area)

You can use the attribute [Routearea] to specify that a controller belongs to a zone, and when you do so, you can safely remove the Arearegistration class for that zone:

1 [Routearea ("Admin")] 2 [Routeprefix ("menu")] 3 [Route ("{action}")] 4 public class Menucontroller:controller 5 {6     Eg:/admin/menu/login 7 public     ActionResult login () {...} 8   9     //eg:/admin/menu/show-options10     [Rou Te ("show-options")]11 public     actionresult options () {...}     //eg:/stats14     [Route ("~/stats")]15 public     ActionResult stats () {...} 16}

Using the controller, the following link will produce the following URL: "/admin/menu/show-options"

Url.action ("Options", "menu", new {area = "Admin"})

You can also use the Areaprefix parameter to create a custom zone prefix, for example:

[Routearea ("BackOffice", Areaprefix = "Back-office")]

If you are using both a zone with routing characteristics and a zone with a traditional route (created by the Arearegistration Class), you should register the zone before the default traditional route after configuring the MVC routing feature, for the simple reason that The order of the route registration must be from the most precise matching rule to the normal matching rule, and finally the fuzzy matching rule, which avoids the early matching of the fuzzy rule in the route matching, and the relative exact match does not have any effect. This is shown in the following example:

1 public static void RegisterRoutes (RouteCollection routes) 2 {3     routes. Ignoreroute ("{resource}.axd/{*pathinfo}"); 4   5     routes. Mapmvcattributeroutes (); 6   7     arearegistration.registerallareas (); 8   9     routes. MapRoute         Name: "Default",         URL: "{controller}/{action}/{id}",         defaults:new {controller = "Home" , action = "Index", id = urlparameter.optional}13     ); 14}

Summarize

This article mainly learn the new features of the ASP. NET MVC5 route, in view of the information of MVC5, see an article, feel good, take a serious look again, try to use their own language translated the original text, perhaps there is translation is not in place, hope Understanding, if you English good, also can refer to the original text.

Original address: Http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

ASP. Mvc]asp.net MVC5 Series--routing Features

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.