none
Applies constraint to specific defined routing in web api RRS feed

  • Question

  • currently I have the following custom constraint in web api:

    IntegerConstraint.cs:

    public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
    {
        if (values.TryGetValue(parameterName, out object value) && value != null)
        {
            string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
    
            if (int.TryParse(valueString, out int resultValue) && (resultValue > 0 && resultValue <= int.MaxValue))
                return true;
            else
                return false;
        }
    
        return false;
    }

    And I registered it at:

    WebApiConfig.cs

    public static void Register(HttpConfiguration config)
    {
        var constraintResolver = new DefaultInlineConstraintResolver();
    
        constraintResolver.ConstraintMap.Add("Integer", typeof(IntegerConstraint));
    
        config.MapHttpAttributeRoutes(constraintResolver);
    
        config.Routes.MapHttpRoute(
            name: "MyWebAPI",
            routeTemplate: "{controller}/{action}"
        );
    }

    And I have used it in controller like:

    [HttpGet]
    [Route("API/GetID/{id:Integer}")]
    public IHttpActionResult GetID([FromUri] int id) { ... }

    It works fine, but when I have another method that have route and call it like this:

    [Route("API/GetID/Something")]
    http://localhost/API/GetID/Something

    it will trigger the IntegerConstraint class with "Something" as it is value, even though I didn't specify:

    :Integer

    in the route attribute

    It works fine when I access like this and have a route like this (with 5 being the value):

    [Route("API/GetID/{id:Integer}")]
    http://localhost/API/GetID/5

    Is there any ways that I can specify only method that have {anyParameterName:Integer} only will call the IntegerConstraint class?

    I have suspected the MapHttpRoute in WebApiConfig that cause any routing that have similar like this will get called the IntegerConstraint class:

    [Route("API/GetID/*something goes here")]
    config.Routes.MapHttpRoute(
                        name: "MyWebAPI",
                        routeTemplate: "{controller}/{action}"
                    );

    Any idea on how to solve this issue?

    Your answer much appreciated.

    Thanks


    Freelancer Programmer

    Saturday, November 25, 2017 4:15 PM

All replies