Web API Attribute Routing Route Prefix in WEB API

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.

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.

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 id)
        {
            List<string> CourseList = new List<string>();

            if (id == 1)
                CourseList = new List<string>() { "ASP.NET", "C#.NET", "SQL Server" };
            else if (id == 2)
                CourseList = new List<string>() { "ASP.NET MVC", "C#.NET", "ADO.NET" };
            else if (id == 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 an entire controller by using the [RoutePrefix] attribute:

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.

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 id)
        {
            List<string> CourseList = new List<string>();

            if (id == 1)
                CourseList = new List<string>() { "ASP.NET", "C#.NET", "SQL Server" };
            else if (id == 2)
                CourseList = new List<string>() { "ASP.NET MVC", "C#.NET", "ADO.NET" };
            else if (id == 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”.

Attribute Routing Route Prefix in WEB API

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

Attribute Routing Route Prefix in WEB API

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.

Attribute Routing Route Prefix in WEB API

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

Attribute Routing Route Prefix in WEB API

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

What is the use of 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 will discuss Web API Route Constraint in Attribute Routing.

SUMMARY

In this article, I try to explain the Web API Attribute Routing Route Prefix with some examples. I hope this Web API Attribute Routing Route Prefix 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 *