Route Names and Route Orders in Attribute Routing

Route Names and Route Orders in Attribute Routing

In this article, I will discuss the Route Names and Route Orders in Attribute Routing with examples. We are going to work with the same example that we worked in our previous articles. So if you have not read those articles then I strongly recommend you to 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

Route Constraints in Attribute Routing

Route Names

In ASP.NET Web API, each and every route has a name. The Route names are useful for generating links so that you can include a link in an HTTP response.

To specify the route name, we need to set the Name property on the attribute. Let us see an example to understand how to set the route name, and also how to use the route name when generating a link.

namespace AttributeRoutingInWEBAPI.Controllers
{
    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:nonzero}", Name = "GetStudentById")]
        public Student GetStudentDetails(int studentID)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
            return studentDetails;
        }

        [Route("api/students")]
        public HttpResponseMessage Post(Student student)
        {
            students.Add(student);
            var response = Request.CreateResponse(HttpStatusCode.Created);

            // Generate a link for the new student and set the Location header in the response.
            string uri = Url.Link("GetStudentById", new { studentID = student.Id });
            response.Headers.Location = new Uri(uri);

            return response;
        }
    }
}
Let’s test this using Fiddler.

Route Names and Route Orders in Attribute Routing

Then click on the execute button. It will give us the below result.

Route Names and Route Orders in Attribute Routing

Route Order

When the WEB API Framework tries to match a URI with a route, it evaluates the routes in a particular order. To specify the order, set the Order property on the route attribute. Lower values are evaluated first. The default order value is zero.

Here is how the total ordering is determined:

  1. Compare the Order property of the route attribute.
  2. Look at each URI segment in the route template. For each segment, order as follows:
  3. Literal segments.
  4. Route parameters with constraints.
  5. Route parameters without constraints.
  6. Wildcard parameter segments with constraints.
  7. Wildcard parameter segments without constraints.
  8. In the case of a tie, routes are ordered by a case-insensitive ordinal string comparison (OrdinalIgnoreCase) of the route template.

Here is an example. Suppose you define the following controller:

Route Names and Route Orders in Attribute Routing

These routes are ordered as follows.
  1. orders/details
  2. orders/{id}
  3. orders/{customerName}
  4. orders/{*date}
  5. orders/pending

Notice that “details” is a literal segment and appears before “{id}”, but “pending” appears last because the Order property is 1. (This example assumes there are no customers named “details” or “pending”. In general, try to avoid ambiguous routes. In this example, a better route template for GetByCustomeris “customers/{customerName}” )

In this article, I try to explain the Route Names and Route Orders in Attribute Routing with examples. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

2 thoughts on “Route Names and Route Orders in Attribute Routing”

Leave a Reply

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