Problem
How to limit the values of parameters in a route.
Solution Solutions
The ASP. NET WEB API allows us to set routing constraints through the Ihttprouteconstraint interface. Both centralized and direct routing can use Ihttprouteconstraint.
The framework provides 18 interfaces that provide most types of constraints, such as constraints related to the length of a route parameter, to ensure that values are within the defined range, or to restrict data types. Of course, you can also customize the constraint logic by implementing the interface Ihttprouteconstraint.
Working principle
Ihttproutconstraint is an HTTP routing constraint interface (such as code snippet 3-11) and exposes a simple method of Match, which requires five arguments, Httprequestmessage instances, Ihttproute instances, The type of parametername,idictionary<string,object> of type String type Value,httproutedirection routedirection, It is also to ensure that the routing can be matched based on the logic of the application.
Code Snippet 3-11 Ihttprouteconstraint definition
Public Interface ihttprouteconstraint{ boolstring parametername, IDictionary< StringObject> values, Httproutedirection routedirection);}
You can also use Compoundrouteconstraint for compound constraints, which need to be added to the Ihttprouteconstraint collection through constructors, as shown in table 3-1, showing the built-in constraints and basic usage
Table 3-1. Constraints that can be used in the ASP. Ihttprouteconstraint WEB API
Property routing, which is the version and actual type of the embedded constraint that is mapped by Defaultinlineconstraintresolver. When Maphttpatrributeroute is called, the ASP. NET WEB API uses parser transformations to embed the constraint into the associated Ihttprouteconstraint instance. In order to handle custom constraints with some constraints, you can also modify Defaultinlineconstraintresolver or implement all of the Iinineconstraintreslover interfaces yourself. In any case, it is necessary to pass one of his examples to the method Maphttpattributeroute.
Optionalrouteconstraint is used to provide optional parameter functions, as described in the previous article 3-4, and also provides a common constraint function. If the route parameter is not routeparameter.optional, Optionalrouteconstraint will only calculate the constraint.
Code Demo
For centralized routing, the constraint is passed in as a third parameter of the Maphttproute method. Similar to the default value, it has been introduced in the 3-3 section, the type of the parameter is Idictionary<string,object>, but the design of the framework can also be passed an anonymous object, the actual type of the method signature is a simple object. The name of the constraint parameter must match the routing template and the signature of the Action.
CONFIG. Routes.maphttproute ( "defaultapi", "orders/{text }", newnew alpharouteconstraint ()}, Null );
With centralized routing, you can also define an embedded regular expression for a string without using any of the Ihttprouteconstarint interfaces. In the plum below, "id" is a number-constrained embedded regular expression.
CONFIG. Routes.maphttproute ( "defaultapi", "Size/{id}" ", new"\d+"} , Null );
Centralized routing can also constrain the HTTP method, as long as it passes a predefined HttpMethod key and assigns a value of Httpmethodconstrtin.
CONFIG. Routes.maphttproute ( "defaultapi", "Size/{id}" ", newnew httpmethodconstraint (Httpmethod.get)}, null );
For direct routing, you can add a colon plus a constraint to the parameter.
[Route ("Orders/{text:alpha}")] Public Httpresponsemessage Get (string text) {}
For the definition of a composite route, centralized routing needs to be transformed by Compoundrouteconstraint.
CONFIG. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Orders/{text}", Constraints:New{text=NewCompoundrouteconstraint (NewList<ihttprouteconstraint> {NewAlpharouteconstraint (),NewMaxlengthrouteconstraint (5)}}, defaults:NULL );
For attribute routing, different constraints can be chained by colons; The framework uses COMPOUNDROUTECONSTRAINT to build composite constraints internally.
[Route ("orders/{text:alpha:maxlength (5)}")] Public Httpresponsemessage Get (string text) {}
A simple custom routing constraint ensures that the parameter is a legitimate email format, as shown in code snippet 3-12. Because the route value is Idictionary<string.object>, it needs to be converted to the desired type (this is string) before validating the constraint.
Public classemailrouteconstraint:ihttprouteconstraint{ Public BOOLMatch (httprequestmessage request, Ihttproute route,stringparametername, IDictionary<string,Object>values, httproutedirection routedirection) { Objectvalue; if(values.) TryGetValue (ParameterName, outValue) && Value! =NULL) { varStringValue = value as string; if(StringValue = =NULL)return false; Try { varemail =Newmailaddress (stringvalue); return true; } Catch(FormatException) {return false; } } return false; }}
This constraint is used directly in a centralized route, as with built-in constraints.
CONFIG. Routes.maphttproute ( "Email", "{controller}/ Email/{text}", newnew emailrouteconstraint ()}, null );
However, when using attribute routing, aliases can be used instead, but there is no such definition in the Emailrouteconstraint class. Because aliases and constraint types are mapped through defaultinlineconstraintreslover, the ASP. NET WEB API uses this to resolve this constraint, and we need to do the following steps
var New defaultinlineconstraintresolver (); ConstraintResolver.ConstraintMap.Add ("email") typeof (emailrouteconstraint)); config. Maphttpattributeroutes (constraintresolver);
In this way, you can use the email constraints defined above, just like the constraints provided by the framework.
[Route ("orders/client/{text:email}")] Public Httpresponsemessage getbyclient (string text) {}
Note If there is no additional mapping step, the constraint does not react, but the entire property route for the ASP. NET WEB API may be problematic.
[Boiled ASP. NET Web API2 methodology] (3-5) Routing constraints