Web API Attribute Routing Route Prefix

ASP.NET Web API Attribute Routing Route Prefix

In this article, I am going to discuss the Web API Attribute Routing Route Prefix with some examples. We are going to work with the same example that we started in Web API Attribute Routing article and continue in Optional Parameters in Web API Attribute Routing article of this Web API article series.

ASP.NET Web API Attribute Routing Route Prefix

Let’s understand the use of Web API Attribute Routing Route Prefix with one example. Let’s modify the StudentController class as shown below.

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

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("students")]
        public IEnumerable<Student> GetAllStudents()
        {
            return students;
        }
        [HttpGet]
        [Route("students/{studentID}")]
        public Student GetStudentByID(int studentID)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
            return studentDetails;
        }
        [HttpGet]
        [Route("students/{studentID}/courses")]
        public IEnumerable<string> GetStudentCourses(int studentID)
        {
            List<string> CourseList = new List<string>();
            if (studentID == 1)
                CourseList = new List<string>() { "ASP.NET", "C#.NET", "SQL Server" };
            else if (studentID == 2)
                CourseList = new List<string>() { "ASP.NET MVC", "C#.NET", "ADO.NET" };
            else if (studentID == 3)
                CourseList = new List<string>() { "ASP.NET WEB API", "C#.NET", "Entity Framework" };
            else
                CourseList = new List<string>() { "Bootstrap", "jQuery", "AngularJs" };
            return CourseList;
        }
    }
}

As you can see from the above example, we are using the route attributes at the action level to define the routes, and furthermore, all the routes in the StudentsController start with the same prefix – students that mean students is the common prefix for all the routes available in the Student Controller.

Here, you can set the common prefix “students” for the entire Student Controller by using the [RoutePrefix] attribute as shown below at the controller level.

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

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]
        //This will be translated to /students 
        public IEnumerable<Student> GetAllStudents()
        {
            return students;
        }
        [HttpGet]
        [Route("{studentID}")]
        //This will be translated to /students/2
        public Student GetStudentByID(int studentID)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
            return studentDetails;
        }
        [HttpGet]
        [Route("{studentID}/courses")]
        //This will be translated to /students/2/course
        public IEnumerable<string> GetStudentCourses(int studentID)
        {
            List<string> CourseList = new List<string>();
            if (studentID == 1)
                CourseList = new List<string>() { "ASP.NET", "C#.NET", "SQL Server" };
            else if (studentID == 2)
                CourseList = new List<string>() { "ASP.NET MVC", "C#.NET", "ADO.NET" };
            else if (studentID == 3)
                CourseList = new List<string>() { "ASP.NET WEB API", "C#.NET", "Entity Framework" };
            else
                CourseList = new List<string>() { "Bootstrap", "jQuery", "AngularJs" };
            return CourseList;
        }
    }
}

The Route Prefix attribute eliminates the need to repeat the common prefix “students” on each and every controller action method. However, sometimes we may need to override the route prefix attribute. Let us understand this with an example

First, add a class file with the name “Teacher.cs” within the Models Folder. To do so right-click on the model’s folder, and then add a new class file with the name “Teacher.cs”. Then Copy and paste the following code in it.

namespace AttributeRoutingInWEBAPI.Models
{
    public class Teacher
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Add the below GetTeachers() action method within the “StudentsController”.

Web API Attribute Routing Route Prefix

After adding the GetTeachers() action in the “StudentsController” class, we want GetTeachers() action to be mapped to the URI tech/teachers“.  

ASP.NET Web API Attribute Routing Route Prefix

If we use the [Route] attribute on GetTeachers() method as shown in the above image and when we navigate to tech/teachers, we get the following error.

Route Prefix in Attribute Routing

But if we navigate to /students/tech/teachers then we get the output as expected that the list of teachers. This is because the [RoutePrefix(“students”)] attribute on StudentsController. Now the question that comes to our mind is how to override the RoutePrefix attribute used in the StudentsController. To override the RoutePrefix we need to use the ~ (tilde) symbol as shown below.

Removing Route Prefix in Attribute Routing

With the above change, now the GetTeachers() action method is mapped to URI “/tech/teachers” as expected.

What is the use of the RoutePrefix attribute?

The RoutePrefix attribute is used to specify the common route prefix at the controller level to eliminate the need to repeat the common route prefix on each and every controller action.

How to override the route prefix? 

Use ~ character to override the route prefix 

In the next article, I am going to discuss Web API Route Constraint in Attribute Routing. Here, In this article, I try to explain the Web API Attribute Routing Route Prefix with some examples. I hope you enjoy this article.

2 thoughts on “Web API Attribute Routing Route Prefix”

  1. In the code below i can’t sent a request to it. So i change a param from “id” to “studentID” and it work.
    [HttpGet]
    [Route(“{studentID}/courses”)]
    //This will be translated to /students/2/course
    public IEnumerable GetStudentCourses(int id)
    {
    List CourseList = new List();
    if (id == 1)
    CourseList = new List() { “ASP.NET”, “C#.NET”, “SQL Server” };
    else if (id == 2)
    CourseList = new List() { “ASP.NET MVC”, “C#.NET”, “ADO.NET” };
    else if (id == 3)
    CourseList = new List() { “ASP.NET WEB API”, “C#.NET”, “Entity Framework” };
    else
    CourseList = new List() { “Bootstrap”, “jQuery”, “AngularJs” };
    return CourseList;
    }

Leave a Reply

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