如何在MVC6中注册RouteConstraints

bil*_*-io 5 c# asp.net asp.net-web-api-routing asp.net-core-mvc asp.net-core

有许多关于如何在以前的MVC版本中创建RouteConstraints的教程:

这如何与MVC6一起使用,特别是注册自定义路由约束,因此它可以用在ApiController动作的属性中?

我创建了一个名为NonEmptyGuid的自定义路由约束,它实际上只是确保将非空Guid用作GET操作的参数:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题: 如何以及在何处为MVC6应用程序注册此自定义RouteConstraint (例如,在WebApi项目中).

Kir*_*lla 0

您可以使用RouteOptions来注册您的约束:

services.Configure<RouteOptions>(options =>
                                options
                                .ConstraintMap
                                .Add("test", typeof(TestRouteConstraint)));
Run Code Online (Sandbox Code Playgroud)