Route Prefix in Attribute Routing

Route Prefix in Attribute Routing

In this article, I will discuss the Route Prefix in Attribute Routing with one example. We are going to work with the same example that we started in Attribute Routing article of this article series. Please read Attribute Routing before proceeding to this article.

Route Prefix

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

namespace AttributeRoutingDemoInMVC.Controllers
{
    public class StudentsController : Controller
    {
        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 ActionResult GetAllStudents()
        {
            return View(students);
        }

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

        [HttpGet]
        [Route("students/{studentID}/courses")]
        public ActionResult 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" };

            ViewBag.CourseList = CourseList;

            return View();
        }
    }
}

As you can see from the above example, we are using route attributes at the action level to define 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 in Student Controller.

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

namespace AttributeRoutingDemoInMVC.Controllers
{
    [RoutePrefix("students")]
    public class StudentsController : Controller
    {
        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 ActionResult GetAllStudents()
        {
            return View(students);
        }

        [HttpGet]
        [Route("{studentID}")]
        //This will be translated to /students/2
        public ActionResult GetStudentByID(int studentID)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
            return View(studentDetails);
        }

        [HttpGet]
        [Route("{studentID}/courses")]
        //This will be translated to /students/2/course
        public ActionResult 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" };

            ViewBag.CourseList = CourseList;

            return View();
        }
    }
}

This Route Prefix eliminates the need to repeat the common prefix “students” on each and every controller action method.

However, sometimes you 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 models folder, and add a new class file. Name it “Teacher.cs”, and then Copy and paste the following code.

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

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

public ActionResult GetTeachers()
{
    List<Teacher> teachers = new List<Teacher>()
            {
                new Teacher() { Id = 1, Name = "James" },
                new Teacher() { Id = 2, Name = "Patrik" },
                new Teacher() { Id = 3, Name = "Smith" }
            };
    return View(teachers);
}

After adding the GetTeachers() action method the “StudentsController” class should look as shown below

namespace AttributeRoutingDemoInMVC.Controllers
{
    [RoutePrefix("students")]
    public class StudentsController : Controller
    {
        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 ActionResult GetAllStudents()
        {
            return View(students);
        }

        [HttpGet]
        [Route("{studentID}")]
        //This will be translated to /students/2
        public ActionResult GetStudentByID(int studentID)
        {
            Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
            return View(studentDetails);
        }

        [HttpGet]
        [Route("{studentID}/courses")]
        //This will be translated to /students/2/course
        public ActionResult 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" };

            ViewBag.CourseList = CourseList;

            return View();
        }

        public ActionResult GetTeachers()
        {
            List<Teacher> teachers = new List<Teacher>()
            {
                new Teacher() { Id = 1, Name = "James" },
                new Teacher() { Id = 2, Name = "Patrik" },
                new Teacher() { Id = 3, Name = "Smith" }
            };
            return View(teachers);
        }
    }
}

Next, add GetTeachers.cshtml view and copy and paste the below code.

GetTeachers.cshtml

@model IEnumerable<AttributeRoutingDemoInMVC.Models.Teacher>
@{
    ViewBag.Title = "GetTeachers";
}
<h2>GetTeachers</h2>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
        </tr>
    }
</table>

We want GetTeachers() method to be mapped to URI “/tech/teachers“.

[Route("tech/teachers")]
public ActionResult GetTeachers()
{
    List<Teacher> teachers = new List<Teacher>()
            {
                new Teacher() { Id = 1, Name = "James" },
                new Teacher() { Id = 2, Name = "Patrik" },
                new Teacher() { Id = 3, Name = "Smith" }
            };
    return View(teachers);
}

If we use the [Route] attribute on GetTeachers() method as shown above 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. So there is definitely a need to override the RoutePrefix used on the StudentsController. To override the RoutePrefix use ~ as shown below

[Route("~/tech/teachers")]
public ActionResult GetTeachers()
{
    List<Teacher> teachers = new List<Teacher>()
            {
                new Teacher() { Id = 1, Name = "James" },
                new Teacher() { Id = 2, Name = "Patrik" },
                new Teacher() { Id = 3, Name = "Smith" }
            };
    return View(teachers);
}
With this change GetTeachers() action method is now mapped to URI “/tech/teachers” as expected.

What is the use of RoutePrefix attribute?

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

How to override the route prefix? 

Use ~ character to override the route prefix

In the next article, I will discuss Route Constraint in Attribute Routing.

SUMMARY

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