ASP.NET Core Attribute Routing using Tokens

ASP.NET Core Attribute Routing using Tokens

In this article, I am going to discuss the ASP.NET Core Attribute Routing using Tokens with Examples. Please read our previous article before proceeding to this one, as we will work with the same example that we worked on in our previous article. Our previous article discussed Attribute Routing in ASP.NET Core MVC Applications. As part of this article, we are going to discuss the following pointers.

  1. Understanding Tokens in Attribute Routing.
  2. Token Example in Attribute Routing.
  3. Advantages of using Tokens in Attribute Routing.
  4. Do we need to write the action token on each action method?
  5. Attribute Routing vs Conventional Routing in ASP.NET Core.
Tokens in Attribute Routing:

In ASP.NET Core, attribute routing allows us to create dynamic and parameterized routes by using tokens in the route template. These tokens are replaced with actual values during URL generation and routing, making your routes more flexible and capable of handling various scenarios.

In ASP.NET Core, the Route Attribute supports Token Replacement. It means we can enclose the token (i.e., controller and action) within a pair of square braces ([ ]). The tokens (i.e., [controller] and [action]) are then replaced with the values of the controller and action method name where the route is defined. If this is unclear now, don’t worry; you will understand this concept once we discuss the example.

Token Example in Attribute Routing:

Let us understand Token Replacement in ASP.NET Core Attribute Routing with an example. Please modify the Home Controller class as shown below. Here we are applying the token [controller] on the Home Controller, and at the same time, we are applying the token [action] on all the action methods.

using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    //Using token controller at the Controller level using the Route Attribute
    [Route("[controller]")]
    public class HomeController : Controller
    {
        //Using token action at the Action Method level using the Route Attribute
        [Route("[action]")]
        public string Index()
        {
            return "Index() Action Method of HomeController";
        }

        //Using token action at the Action Method level using the Route Attribute
        [Route("[action]")]
        public string Details()
        {
            return "Details() Action Method of HomeController";
        }
    }
}

With the above controller and action tokens in place with the Route Attribute, you can now access the Index action method of the Home Controller with the URL /Home/Index. Similarly, you can access the Details action method of the Home Controller using the URL /Home/Details.

Now run the application and see if everything is working as expected. So, basically, the token controller will be replaced with the actual controller name, and similarly, the token action will be replaced with the actual action method name.

Advantages of Tokens in ASP.NET Core MVC Attribute Routing:

The main advantage of using tokens in ASP.NET Core Attribute Routing is that in the future, if you rename the controller name or the action method name, then you do not have to change the Route templates. The application is going to work with the new controller and action method names.

How to Make the Index Action Method the Default Action?

With the controller and action tokens in place with Route Attribute, if you want to make the Index action method of Home Controller the default action, then you need to include the [Route(“/”)] attribute with an “/” on the Index action method. So, modify the Home Controller as shown below and rerun the application, and it should display the Index Action method.

using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    //Using token controller at the Controller level using the Route Attribute
    [Route("[controller]")]
    public class HomeController : Controller
    {
        //Using token action at the Action Method level using the Route Attribute
        [Route("/")] //This will make the Index Action method as the Default Action
        [Route("[action]")]
        public string Index()
        {
            return "Index() Action Method of HomeController";
        }

        //Using token action at the Action Method level using the Route Attribute
        [Route("[action]")]
        public string Details()
        {
            return "Details() Action Method of HomeController";
        }
    }
}
Do we need to write the action token on each action method?

Not Really. If you want all your action methods to apply the action token, then instead of including the [action] token on each and every action method, you can apply it only once on the controller. So, in this case, the Route attribute at the controller level should include both controller and action tokens like [Route(“[controller]/[action]”)]. So, modify the Home Controller class as shown below to apply the controller and action tokens at the controller level.

using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    //Using controller and action tokens at the Controller level using the Route Attribute
    [Route("[controller]/[action]")]
    public class HomeController : Controller
    {
        //This will make the Index Action method as the Default Action
        [Route("/")]
        public string Index()
        {
            return "Index() Action Method of HomeController";
        }

        public string Details()
        {
            return "Details() Action Method of HomeController";
        }
    }
}

Attribute routing with tokens provides a flexible and expressive way to define dynamic routes in your ASP.NET Core MVC application.

Attribute Routing vs Conventional Routing in ASP.NET Core:

In Attribute Routing, we need to define the routes using the Route attribute within the controller and action methods. Attribute routing offers a bit more flexibility than conventional-based routing. However, conventional-based routings are generally useful for controllers that serve HTML pages. On the other hand, attribute routings are useful for controllers that serve RESTful APIs. However, there is nothing stopping you from mixing conventional-based routing with attribute routing in a single application.

Attribute routing and conventional routing are two different approaches for defining routes in ASP.NET Core MVC. Each approach has its own advantages and use cases. Let’s compare attribute routing and conventional routing in ASP.NET Core:

Attribute Routing:
  1. Explicitness and Readability: Attribute routing allows you to define routes directly on your controller actions and methods using attributes. This makes the routing configuration more explicit and readable, as the route template is defined exactly where the action is.
  2. Fine-Grained Control: Attribute routing provides fine-grained control over individual routes. You can define custom route templates, constraints, and HTTP methods for each action, allowing for more flexible and specific routing configurations.
  3. RESTful API Design: Attribute routing is well-suited for designing RESTful APIs, where you can create meaningful and predictable URLs that align with REST conventions.
  4. Localization and Globalization: Attribute routing can be combined with localization, and globalization features in ASP.NET Core to create localized URLs and content.
  5. Reduced Boilerplate: Attribute routing can reduce the need for separate routing configuration files, resulting in less boilerplate code and potentially easier maintenance.
  6. Clearer Separation of Concerns: Attribute routing enhances the separation of concerns by keeping routing information closer to the action methods.
Conventional Routing:
  1. Convention-Over-Configuration: Conventional routing follows a convention-based approach, where routes are defined globally and inferred based on naming conventions. This can lead to less explicit configuration, but it also means that you don’t need to explicitly define routes for every action.
  2. Centralized Configuration: Conventional routing allows you to define routes in a central location (usually in the Program.cs file), which can be advantageous for projects with a large number of controllers and actions.
  3. Simplicity: Conventional routing can be simpler for basic scenarios where you don’t require the fine-grained control that attribute routing offers.
  4. Existing Applications: If you’re migrating an existing application from an older version of ASP.NET MVC, you might already have conventional routing in place. Converting to attribute routing could be a gradual process.

In short, attribute routing is preferred when you need more control over individual routes, want to design RESTful APIs, or are looking for a more explicit and self-contained way to define routes. Conventional routing might be a better fit for simpler scenarios or for projects where a central configuration approach is preferred. In practice, many ASP.NET Core applications use a combination of both attribute and conventional routing, depending on the specific needs of different parts of the application.

In the next article, I am going to discuss Layout View in ASP.NET Core MVC Application with one example. I explain the need and use of ASP.NET Core Attribute Routing using Tokens in this article. I hope you enjoy this Token Replacement in ASP.NET Core Attribute Routing article. 

1 thought on “ASP.NET Core Attribute Routing using Tokens”

Leave a Reply

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