Loading

ASP.NET Web API

What is ASP.NET Web API Attribute Routing Route Constraints?. The Complete ASP.NET Web API Developer Course 2022 [Videos].

In this Video, I will discuss the Web API Attribute Routing Route Constraints with examples. We are going to work with the same example that we worked in our previous Videos. So, please watch the following Videos before proceeding to this Video. 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.

Lets 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. 

Lets change our business requirement, in addition to retrieving the student details by “student Id”, we also want to retrieve the student details by “student Name“. So lets 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 URIs

/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/Pranayathen 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 the 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.

Lets 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 URIs 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 the “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;
}

See All

Comments (330 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET Web API / Blog

What is ASP.NET Web API Application?

In this ASP.NET Web API Tutorials series, I covered all the features of ASP.NET Web API. You will learn from basic to advance level features of ASP.NET Web API. The term API stands for “Application Programming Interface” and ASP.NET Web API is a framework provided by Microsoft which makes it easy to build Web APIs, i.e. it is used to develop HTTP-based web services on the top of .NET Framework.
3-Feb-2022 /34 /330

ASP.NET Web API / Blog

How to creat ASP.NET Web API Application using Visual Studio?

In this article, I am going to discuss the step-by-step procedure for Creating ASP.NET Web API Application. Please read our previous article before proceeding to this article where we gave an overview of the ASP.NET Web API framework. As part of this article, we ate going to discuss the following pointers.
3-Feb-2022 /34 /330

ASP.NET Web API / Blog

How to add Swagger in Web API Application?

In this article, I am going to discuss how to add Swagger in Web API Application to document and test restful Web API services. Please read our previous article where we discussed How to Create an ASP.NET Web API Application step by step before proceeding to this article as we are going to work with the same example. As part of this article, we are going to discuss the following pointers.
3-Feb-2022 /34 /330