问题
There are numerous tutorials on how to create RouteConstraints in previous MVC versions:
- Registering ASP.NET MVC Route Constraints for Attribute Routing
- Constraints in Attribute-based Routing MVC5
How does this work with MVC6, specifically registering the custom route constraint, so it can be used in attributes of ApiController Actions?
I have created a custom route constraint, called NonEmptyGuid, which really just makes sure a non-empty Guid is used as the parameter of a GET Action:
public class NonEmptyGuid : IRouteConstraint
{
public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection)
{
if (!values.ContainsKey(routeKey)) return false;
if (values[routeKey].ToString().Equals(Guid.Empty.ToString())) return false;
return true;
}
}
Question: How and where does one register this custom RouteConstraint for an MVC6 application (e.g. in this case in a WebApi Project).
回答1:
You can use RouteOptions to register your constraints:
services.Configure<RouteOptions>(options =>
options
.ConstraintMap
.Add("test", typeof(TestRouteConstraint)));
来源:https://stackoverflow.com/questions/32583743/how-to-register-routeconstraints-in-mvc6