Web API Attribute Routing Route Constraints

ASP.NET Web API Attribute Routing Route Constraints

In this article, I will discuss the Web API Attribute Routing Route Constraints with examples. We are going to work with the same example that we worked with our previous articles. So, please read the following articles before proceeding to this article.

Attribute Routing in Web API

Optional URI Parameters and Default values in Attribute Routing

Attribute Routing Route Prefix in WEB API

Web API Attribute Routing Route Constraints

The Web API Attribute Routing Route Constraints are nothing but a set of rules that we can apply on our routing parameters to restrict how the parameters in the route template are matched. The general syntax is

{parameter:constraint}

Let us understand ASP.NET Web API Attribute Routing Route Constraints with one example.

Let’s modify the Students Controller as shown below.

namespace AttributeRoutingInWEBAPI.Controllers
{
    [RoutePrefix("students")]
    public class StudentsController : ApiController
    {
        static List<Student> students = new List<Student>()
        {
            new Student() { Id = 1, Name = "Pranaya" },
            new Student() { Id = 2, Name = "Priyanka" },
            new Student() { Id = 3, Name = "Anurag" },
            new Student() { Id = 4, Name = "Sambit" }
        };

        [HttpGet]
        [Route("{studentID}")]
        public Student GetStudentDetails(int studentID)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
            return studentDetails;
        }
    }
}

Now, if we navigate to /students/1 URI, then the GetStudentDetails(int studentID) action is executed and we get the details of the student whose id is 1 as expected. 

Let’s change our business requirement, in addition to retrieving the student details bystudent Id”, we also want to retrieve the student details bystudent Name“. So let’s add another GetStudentDetails() action method with a string parameter as shown below.

namespace AttributeRoutingInWEBAPI.Controllers
{
    [RoutePrefix("students")]
    public class StudentsController : ApiController
    {
        static List<Student> students = new List<Student>()
        {
            new Student() { Id = 1, Name = "Pranaya" },
            new Student() { Id = 2, Name = "Priyanka" },
            new Student() { Id = 3, Name = "Anurag" },
            new Student() { Id = 4, Name = "Sambit" }
        };

        [HttpGet]
        [Route("{studentID}")]
        public Student GetStudentDetails(int studentID)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
            return studentDetails;
        }

        [HttpGet]
        [Route("{studentName}")]
        public Student GetStudentDetails(string studentName)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Name == studentName);
            return studentDetails;
        }
    }
}

At this point build the solution, and navigate to the following URI’s

/students/1

/students/Pranaya

In both the cases we will get the below error:

Multiple actions were found that match the request: GetStudentDetails on type AttributeRoutingInWEBAPI.Controllers.StudentsController GetStudentDetails on type AttributeRoutingInWEBAPI.Controllers.StudentsController

This is because the WEB API Framework does not know or does not identify which version of the GetStudentDetails() action method to use. This is the situation where the route constraints play a very important role.

If an integer is specified in the URI like /students/1, then we need to execute the GetStudentDetails(int studentId) action method which takes an integer parameter whereas if a string is specified in the URI like /students/Pranaya, then we need to execute the GetStudentDetails(string studentName) action method which takes the parameter of type string.

This can be very easily achieved using Attribute Route Constraints in WEB API application. To specify the attribute route constraint, the syntax is {parameter:constraint}. With these constraints in place, if the parameter segment in the URI is an integer, then the GetStudentDetails(int studentId) action method with integer parameter is invoked and if it is a string value then the GetStudentDetails(string studentName) action method with string parameter is invoked.

Let’s modify the Student Controller to use the Attribute Route Constraints as shown below to achieve the above requirements.
namespace AttributeRoutingInWEBAPI.Controllers
{
    [RoutePrefix("students")]
    public class StudentsController : ApiController
    {
        static List<Student> students = new List<Student>()
        {
            new Student() { Id = 1, Name = "Pranaya" },
            new Student() { Id = 2, Name = "Priyanka" },
            new Student() { Id = 3, Name = "Anurag" },
            new Student() { Id = 4, Name = "Sambit" }
        };

        [HttpGet]
        [Route("{studentID:int}")]
        public Student GetStudentDetails(int studentID)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
            return studentDetails;
        }

        [HttpGet]
        [Route("{studentName:alpha}")]
        public Student GetStudentDetails(string studentName)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Name == studentName);
            return studentDetails;
        }
    }
}

Now build the solution, and navigate to the following two URI’s and see everything is working as expected.

/students/1

/students/Pranaya

Please note that “alpha” stands for uppercase or lowercase alphabet characters. Along with alpha and int, you can also use constraints such as decimal, float, long, double, bool etc. Please check the following MSDN link for the full list of available constraints in web API.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-constraints

Example: 

If you want GetStudentDetails(int studentId) action method to be mapped to URI /students/{studentId}, only if the studentId is a number greater than ZERO, then use the “min” constraint as shown below. 

WEB API Route Constraints in Attribute Routing

With the above change, if we specify a positive number like 1 in the URI, then it will be mapped to the GetStudentDetails(int studentID) action method as expected

/students/1

However, if we specify 0 or a negative number less than ZERO, then we will get an error. For example, if we specify 0 as the value for studentID in the URI,

/students/0

We will get the below error

WEB API Route Constraints in Attribute Routing

Along with the “min” constraint you can also specify “max” constraint as shown below. For example, if you want the studentID value in the URI to be between 1 and 3 inclusive, then you can specify both “min” and “max” constraints as shown below.

WEB API Route Constraints in Attribute Routing

The above example can also be achieved using the “range” attribute as shown below

WEB API Route Constraints in Attribute Routing

Custom Web API Route Constraints in Attribute Routing

You can also create custom route constraints in Web API and to do so you need to implement the IHttpRouteConstraint interface. For example, the below constraint will restrict a parameter value to a non-zero integer value.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Web.Http.Routing;

namespace AttributeRoutingInWEBAPI.Models
{
    public class NonZeroConstraint : IHttpRouteConstraint
    {
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
            IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            object value;
            if (values.TryGetValue(parameterName, out value) && value != null)
            {
                long longValue;
                if (value is long)
                {
                    longValue = (long)value;
                    return longValue != 0;
                }

                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
                if (Int64.TryParse(valueString, NumberStyles.Integer,
                    CultureInfo.InvariantCulture, out longValue))
                {
                    return longValue != 0;
                }
            }
            return false;
        }
    }
}

The following code shows how to register the custom constraint:

namespace AttributeRoutingInWEBAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var constraintResolver = new DefaultInlineConstraintResolver();
            constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));

            // Attribute routing.
            config.MapHttpAttributeRoutes(constraintResolver);

            // Convention-based routing.
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Now you can apply the custom constraint in your routes as shown below.

[HttpGet]
[Route("{studentName:alpha}")]
public Student GetStudentDetails(string studentName)
{
    Student studentDetails = students.FirstOrDefault(s => s.Name == studentName);
    return studentDetails;
}

In the next article, I will discuss Route Names and Route Orders in WEB API.

SUMMARY

In this article, I try to explain the Web API Attribute Routing Route Constraints with examples. I hope this Web API Attribute Routing Route Constraints article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *