Loading

ASP.NET Web API

How to implement attribute Routing Route Prefix Web API?. The Complete ASP.NET Web API Developer Course 2023 [Videos].

In this article, I am going to discuss the Attribute Routing Route Prefix in Web API 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. At the end of this article, you will understand What is Route Prefix in Web API and when and how to use Web API Route Prefix with an example.

ASP.NET Web API Attribute Routing Route Prefix

Lets understand the use of Web API Attribute Routing Route Prefix with one example. Lets 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 FolderTo do so right-click on the models 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/teacherswe 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 

See All

Comments (329 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 /329

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 /329

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 /329