How To Register RouteConstraints in MVC6

随声附和 提交于 2019-12-12 10:54:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!