Route Prefix in ASP.NET Core Web API Routing

Route Prefix in ASP.NET Core Web API Routing

In this article, I will discuss How to Set Route Prefix in ASP.NET Core Web API Routing with Examples. Please read our previous article discussing the Token Replacement in ASP.NET Core Web API Routing. We will also work with the same application we created in our Routing in ASP.NET Core Web API article.

Route Prefix in ASP.NET Core Web API Routing

In ASP.NET Core Web API, the route prefix is one of the important routing concepts that helps organize and access the API endpoints efficiently. It acts as a common path segment prefixed to the URL of all actions within a controller, making it easier to group similar functionalities and manage the API’s structure. This feature is useful in attribute routing, where routes are defined directly on controllers and actions using attributes.

Let’s understand the need and use of Base Route in ASP.NET Core Web API Routing with an Example. Let us first modify the EmployeeController class as shown below.

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]   
    public class EmployeeController : ControllerBase
    {
        [Route("employee/all")]
        [HttpGet]
        public string GetAllEmployees()
        {
            return "Response from GetAllEmployees Method";
        }

        [Route("employee/{Id}")]
        [HttpGet]
        public string GetEmployeeById(int Id)
        {
            return $"Response from GetEmployeeById Method, Id : {Id}";
        }

        [Route("employee/department/{Department}")]
        [HttpGet]
        public string GetDepartmentEmployees(string Department)
        {
            return $"Response from GetDepartmentEmployees Method, Department : {Department}";
        }
    }
}

Now, you can access the three methods above, as shown in the image below.

Route Prefix in ASP.NET Core Web API Attribute Routing with Examples

As you can see in the above example, we are using the Route attributes at the action level to define the routes, and furthermore, all the routes in the EmployeeController start with the same prefix – employee. That means the employee is the common prefix that is used for all the routes available in the Employee Controller at the moment.

Is it not good enough if you can move the common attribute prefix to the controller level? Yes, we can. So, the common prefix for all the routes should be placed at the controller level, and the route specific to the action method should be placed at the action method level. So, in our example, the common prefix, i.e., employee, should be placed at the controller level, and the rest should be placed at the action method level, as shown below.

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    [Route("employee")]
    public class EmployeeController : ControllerBase
    {
        [Route("all")]
        [HttpGet]
        public string GetAllEmployees()
        {
            return "Response from GetAllEmployees Method";
        }

        [Route("{Id}")]
        [HttpGet]
        public string GetEmployeeById(int Id)
        {
            return $"Response from GetEmployeeById Method, Id : {Id}";
        }

        [Route("department/{Department}")]
        [HttpGet]
        public string GetDepartmentEmployees(string Department)
        {
            return $"Response from GetDepartmentEmployees Method, Department : {Department}";
        }
    }
}

With the above changes in place, you can access the above three resources as we accessed them in our previous example, as shown in the image below.

need and use of Base Route in ASP.NET Core Web API Routing with an Example

With the above changes in place, we eliminate the need to repeat the common prefix “employee” on each and every controller action method. However, sometimes, we may need to override the common route prefix attribute.

How to Define a Route Prefix?

The route prefix is typically defined using the [Route] attribute at the controller level. This attribute specifies the initial segment(s) of the URI that will be common to all actions within that controller. By doing so, you can create a hierarchical URL structure for your API that is logically organized according to the resources or functionalities it exposes.

How do you override the Base Route in ASP.NET Core Web API Attribute Routing?

Let us understand how to override the common route prefix or base route in ASP.NET Core Web API Attribute Routing with an example. Currently, our Employee Controller class contains three action methods, which start with the same Route Prefix, i.e., employee.

We want to add one action method within the employee controller to return all departments. And we want to access this resource using the URL: department/all. So, let us first add the following GetAllDepartment method and decorate it with [Route(“department/all”)] Attribute as shown below within the EmployeeController.

[Route("department/all")]
[HttpGet]
public string GetAllDepartment()
{
    return "Response from GetAllDepartment Method";
}

With the above [Route(“department/all”)] attribute on the GetAllDepartment() method, when we navigate to department/all, we will get the following error.

How to override the Base Route in ASP.NET Core Web API Attribute Routing?

But if we navigate to /employee/department/all, we will get the output as expected, as shown in the image below. This is because the [Route(“employee”)] attribute is defined at the Employee Controller.

How to override the Base Route in ASP.NET Core Web API Attribute Routing?

Now, the question that should come to your mind is how to override the Route attribute used in the EmployeeController, i.e., the Route Attribute defined at the controller level.

How do you override the Controller Level Route Attribute at the action method level?

In the ASP.NET Core Application, you can override the Controller level Route Attribute at the action method level by using the ~ (tilde) symbol. So, modify the GetAllDepartment action method as shown below to use the tilde symbol to override the route defined at the employee controller.

[Route("~/department/all")]
[HttpGet]
public string GetAllDepartment()
{
    return "Response from GetAllDepartment Method";
}

With the above change in place, the GetAllDepartment() action method is now mapped to URI “/department/all” as expected, as shown in the image below.

Route Prefix in ASP.NET Core Web API Attribute Routing

Instead of providing an action-specific route using Route Attribute, we can also specify the same using HTTP methods such as HttpGet, HttpPost, HttpPut, and HttpDelete. To better understand, please modify the Employee Controller as follows and then check each endpoint. It works as expected.

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    [Route("employee")]
    public class EmployeeController : ControllerBase
    {
        //[Route("all")]
        [HttpGet("all")]
        public string GetAllEmployees()
        {
            return "Response from GetAllEmployees Method";
        }

        //[Route("{Id}")]
        [HttpGet("{Id}")]
        public string GetEmployeeById(int Id)
        {
            return $"Response from GetEmployeeById Method, Id : {Id}";
        }

        //[Route("department/{Department}")]
        [HttpGet("department/{Department}")]
        public string GetDepartmentEmployees(string Department)
        {
            return $"Response from GetDepartmentEmployees Method, Department : {Department}";
        }

        //[Route("~/department/all")]
        [HttpGet("~/department/all")]
        public string GetAllDepartment()
        {
            return "Response from GetAllDepartment Method";
        }
    }
}
When should you use Route Prefix in ASP.NET Core Web API Routing?

Here are key scenarios when it’s beneficial to use a route prefix in ASP.NET Core Web API routing:

Organizing APIs into Functional Areas

If your Web API serves different functional areas (e.g., billing, customer management, product inventory), using a route prefix can help organize these into clear, distinct sections. This organization makes the API more understandable and navigable for both developers and clients.

[Route("api/billing/[controller]")]
public class InvoicesController : ControllerBase { /*...*/ }

[Route("api/customer/[controller]")]
public class CustomersController : ControllerBase { /*...*/ }
API Versioning

Route prefixes are particularly useful for versioning APIs. By including the version number in the prefix, you can easily manage and route requests to different versions of your API, allowing for simultaneous support of multiple API versions.

[Route("api/v1/[controller]")]
public class OrdersV1Controller : ControllerBase { /*...*/ }

[Route("api/v2/[controller]")]
public class OrdersV2Controller : ControllerBase { /*...*/ }
Simplifying Route Templates

Applying a route prefix helps avoid repetition in defining route templates for each controller, making your code DRY (Don’t Repeat Yourself). It simplifies the route definition and makes your codebase cleaner and more maintainable.

Enforcing Consistency

Using a route prefix helps enforce a consistent routing structure across your API, making it easier for developers to understand the routing logic and for clients to construct URLs.

Benefits of Using a Route Prefix in ASP.NET Core Web API:
  • Organizational Clarity: By grouping all actions within a controller under a common route prefix, you make the API’s structure clearer and more intuitive. This is especially beneficial in large projects with multiple controllers.
  • Simplification of Routes: Instead of defining the full path for each action, you only need to specify the part of the route that is unique to that action. This reduces redundancy and the potential for typos or inconsistencies in route paths.
  • Versioning: Route prefixes can be used effectively for API versioning. By including the version in the prefix (e.g., api/v1/users), you can manage multiple versions of your API simultaneously with minimal overlap or confusion.

In the next article, I will discuss Route Constraints in ASP.NET Core Web API Attribute Routing with Examples. In this article, I try to explain the Route Prefix in ASP.NET Core Web API Attribute Routing with examples. I hope you enjoy this Route Prefix in the ASP.NET Core Web API Attribute Routing article.

Leave a Reply

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