ASP for the WEB API. NET attribute Routing instance detailed

Source: Internet
Author: User
The following is a general MVC Route

Config. Routes.maphttproute (        name: "Defaultapi",        routetemplate: "Api/{controller}/{id}",        defaults:new {id = Routeparameter.optional},      );

It is cumbersome to use conventional convention routing if we are to implement a route similar to the following effect.

order/miles/Three squirrel dried fruit/2 bag ORDER/2017/1/13

If you use attribute routing, it's easier.

To create a new Web API project, open the WebApiConfig.cs file in the App_start directory and add the following code to turn on the property routing configuration.

Config. Maphttpattributeroutes ();

Attribute routing can also be used in combination with convention routing, as follows:

public static void Register (httpconfiguration config)    {      //Web API Configuration and service      //Web API Route      CONFIG. Maphttpattributeroutes ();      Config. Routes.maphttproute (        name: "Defaultapi",        routetemplate: "Api/{controller}/{id}",        defaults:new {id = Routeparameter.optional},        constraints:new {id=@ "\d+"}      );    

On the method to use attribute routing, mark the attribute as follows:

[Route ("Order/{usernickname}/{productname}/{count}")]

The test results (URLs are encoded, or 400 errors are reported.) )


Typically, all routes in the same controller start with the same prefix

  [Route ("Api/books")]  [Route ("Api/books/{id:int}")]  [Route ("Api/books")]

This is obviously a bit of a hassle. So we use the [Routeprefix] property to set a common prefix

Test results

If you use [Routeprefix], some of the more special APIs, we can use a wavy line to rewrite the route prefix, as follows:

Test results (under the same class)

Parameters can also be included in the route prefix, as follows

Test results


Parameter constraints can be added to the route, as follows

Test results

If the parameter is not of type int, it does not match to the route

Here are some of the constraints that will be supported

Multiple constraints can be used, but separated by colons

[Route ("Users/{id:int:length (1,3)}")]public User Getuserbyid (int id) {...}

Results

If it's not in range, it won't match.

Custom routing constraints, you need to implement the Ihttprouteconstraint interface, specific view of the official

public class nonzeroconstraint:ihttprouteconstraint{Public  bool Match (httprequestmessage request, Ihttproute Route, String parametername,     idictionary<string, object> values, httproutedirection routedirection)  {    object value;    if (values. TryGetValue (parametername, out value) && value! = null)    {      long longvalue;      If (value is long)      {        Longvalue = (long) value;        return longvalue! = 0;      }      String valuestring = convert.tostring (value, cultureinfo.invariantculture);      if (Int64.tryparse (valuestring, Numberstyles.integer,         CultureInfo.InvariantCulture, out Longvalue))      {        return Longvalue! = 0;      }    }    return false;  }}

Registration constraints

public static class webapiconfig{public  static void Register (httpconfiguration config)  {    var Constraintresolver = new Defaultinlineconstraintresolver ();    CONSTRAINTRESOLVER.CONSTRAINTMAP.ADD ("Nonzero", typeof (Nonzeroconstraint));    Config. Maphttpattributeroutes (Constraintresolver);  }}

Working with constraints

[Route ("{Id:nonzero}")]public httpresponsemessage getnonzero (int id) {...}

Optional URI parameters and default values

You can mark a route parameter by adding a question mark to make it an optional URI parameter. If a route parameter is optional, you must define a default value for this method parameter.

public class bookscontroller:apicontroller{  [Route ("Api/books/locale/{lcid:int?}")]  Public ienumerable<book> getbooksbylocale (int lcid = 1033) {...}}

or define default values in the routing template

public class bookscontroller:apicontroller{[Route ("api/books/locale/{lcid=1033}")] Public ienumerable<book> getbooksbylocale (int lcid) {...}} 
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.