Token Replacement in ASP.NET Core Web API Routing

Token Replacement in ASP.NET Core Web API Routing

In this article, I will discuss Token Replacement in ASP.NET Core Web API Routing with Examples. Please read our previous article, which discusses How to Set Up Multiple URLs for a Single Resource in the ASP.NET Core Web API Application. We will also work with the same application we created in our Routing in ASP.NET Core Web API article. 

What are Tokens in ASP.NET Core Attribute Routing?

In ASP.NET Core, attribute routing is a feature that allows us to define routes directly on controllers and actions using Route or HTTP method attributes. Tokens in attribute routing are placeholders that allow us to capture values from the request URI and use them as parameters in route templates.

Tokens are enclosed in square braces [] and can be placed within the route template to capture specific parts of the URI. These captured values can then be used as parameters in your action methods. The following are some standard tokens used in attribute routing:

  • [controller]: Represents the controller name.
  • [action]: Represents the name of the action method.
Example Without Using Token Replacement in ASP.NET Core Web API

Before understanding the need and use of token replacement, let us first understand an example without using token replacement. Suppose we have two resources in our Employee Controller and want to access them using the controller/action name. Then, we can do the same without token replacement, as shown in the code below.

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

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

Now run the application, and you can access both the resource using the controller and action method name, as shown in the below image.

Example Using Token Replacement in ASP.NET Core Web API Application

Let us understand how the token replacement works in the ASP.NET Core Web API Application with an example. Please modify the Employee Controller class that we have been working on so far, as shown below. As you can see, we are applying the token [controller] to the EmployeeController and the token [action] to all its action methods.

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

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

Now, with the above changes in place, you can access the GetAllEmployees method with the URL: /Employee/GetAllEmployees and the GetAllDepartment method with the URL: /Employee/GetAllDepartment, as shown in the image below. This is because at the run time, the token [controller] will be replaced by Employee, and the token [action] will be replaced by the respective action method of the controller.

Do we need to write the action token on each action method?

Not Really. If you want the action token to be applied to all action methods, then you can apply it only once at the controller level instead of including the [action] token on each action method.

Let us understand this with an example. Please modify the Employee Controller class as shown in the below code. As you can see in the below code, we have removed the [Route(“[action]”)] attribute from the action method and modified the Route attribute as [Route(“[controller]/[action]”)], which is applied at the controller level.

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

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

Now, with the above changes in place, you can also access the GetAllEmployees method with the URL: /Employee/GetAllEmployees and the GetAllDepartment method with the URL: /Employee/GetAllDepartment, as shown in the below image.

Token Replacement with Dynamic Values:

Now, let us see an example of token replacement with dynamic values. Our requirement is to fetch employee information using the employee ID. Here, the employee ID is the dynamic value, and this value will come as part of the URL. Let us see how we can achieve this. Here, we need to decorate the Route attribute with the action method, as shown below.

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

So, please modify the Employee Controller class as shown below. Here, you can see we have applied the Route Attribute both at the action method and controller level. At the run time, the [Route(“[controller]/[action]”)] will evaluate first, and then [Route(“{Id}”)] will be added to the route which will form the URL as Employee/GetEmployeeById/10.

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

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

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

With the above changes, run the application and access the GetEmployeeById, as shown in the image below. You should see the response as expected.

Controller and Action token applied to the action method

In the example below, we are applying the Route Attribute only at the action method level, and it will also work as expected.

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

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

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

Using the common part of the Route at the Controller level is always recommended. In the next article, I will discuss How to set the common or base route at the controller level in ASP.NET Core Web API Routing with Examples. In this article, I try to explain token replacement in ASP.NET Core Web API Attribute Routing with examples. I hope you enjoy this Token Replacement in the ASP.NET Core Web API Attribute Routing article.

Leave a Reply

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