Detailed description of ASP. net web api attribute routing, asp. netapi
Common MVC Routing
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, );
If we want to implement a route similar to the following, it is troublesome to use a conventional Convention route.
Order/Miles/three squirrel dried fruits/2 bags order/hour /1/13
It is easier to use Attribute routing.
To create a new web api project, open the WebApiConfig. cs file in the App_Start directory and add the following code to enable attribute routing configuration.
config.MapHttpAttributeRoutes();
Attribute routing can also be used together with Convention routing, as shown below:
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 + "});}
Mark the method to use the property routing as follows:
[Route("order/{UserNickName}/{ProductName}/{count}")]
Test result (the URL is encoded, otherwise error 400 will be reported .)
Generally, 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 troublesome. Therefore, we use the [RoutePrefix] attribute to set a public prefix.
Test Results
If [RoutePrefix] is used, some special APIs can be used to overwrite the routing prefix, as shown below:
Test results (under the same class)
The route prefix can also contain the following parameters:
Test Results
You can add parameter constraints to the route as follows:
Test Results
If the parameter is not of the Int type, the route is not matched.
The following are some constraints that will be supported:
Multiple constraints can be used, but they must be separated by colons.
[Route("users/{id:int:length(1,3)}")]public User GetUserById(int id) { ... }
Result
If it is not in the specified range, it cannot be matched.
To customize route constraints, you must implement the IHttpRouteConstraint interface. For details, see the official website
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); }}
Restrictions
[Route("{id:nonzero}")]public HttpResponseMessage GetNonZero(int id) { ... }
Optional URI parameters and default values
You can add a question mark to mark a route parameter 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 the default value in the routing template.
public class BooksController : ApiController{ [Route("api/books/locale/{lcid=1033}")] public IEnumerable<Book> GetBooksByLocale(int lcid) { ... }}
If you write so many frequently-used ones, check the official website for the rest! I hope it will be helpful for everyone's learning, and I hope you can support the house of helping customers more.