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.
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.
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 models folder, and then add a new class file with the name “Teacher.csâ€. Then Copy and paste the following code in it.
Add the below GetTeachers() action method within the “StudentsControllerâ€.
After adding the GetTeachers() action in the “StudentsController†class, we want GetTeachers() action to be mapped to the URI “tech/teachers“.
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.
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.
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