skip to content

In ASP.NET Core MVC, how are [controller] and [action] tokens in a [Route] template replaced, and how do you make them produce kebab-case URLs?

level: seniorimportance: should knowfreq 32%

answer

  1. replaced when attribute routes are built
  2. [controller], [action], [area]
  3. [[ and ]] for literal brackets
  4. string? TransformOutbound(object? value)
  5. RouteTokenTransformerConvention in MvcOptions.Conventions

basics

~20 s

When MVC builds attribute routes it replaces [controller], [action] and [area] with the controller name without its suffix, the action name and the area. An IOutboundParameterTransformer applied through RouteTokenTransformerConvention rewrites those values, for example BookSeries to book-series.

solid answer

~30 s

Token replacement is the last step of building attribute routes: `[Route("api/[controller]")]` on `BookSeriesController` becomes `api/BookSeries`, and `[HttpGet("[action]")]` on `NewReleases` adds `NewReleases`. It also applies to route names, and a literal bracket is written `[[` or `]]`. To change the replaced text, implement `IOutboundParameterTransformer`, whose `TransformOutbound(object? value)` returns the new string, and register `new RouteTokenTransformerConvention(transformer)` in `MvcOptions.Conventions`. The routes become `/api/book-series/new-releases`, and `Url.Action` generates the same form. For conventional routes, put the transformer in the template, `{controller:slugify=Home}`, after registering it in `RouteOptions`. It does not touch Razor Pages routes, which use `PageRouteTransformerConvention`.

code

csharp · 26 lines
csharp
using System.Text;
using Microsoft.AspNetCore.Mvc.ApplicationModels;

var builder = WebApplication.CreateBuilder(args);
// BookSeriesController.NewReleases -> /api/book-series/new-releases
builder.Services.AddControllers(options =>
    options.Conventions.Add(
        new RouteTokenTransformerConvention(new SlugifyParameterTransformer())));
var app = builder.Build();
app.MapControllers();
app.Run();

public sealed class SlugifyParameterTransformer : IOutboundParameterTransformer
{
    public string? TransformOutbound(object? value)
    {
        if (value?.ToString() is not { Length: > 0 } text) return null;
        var sb = new StringBuilder(text.Length + 8);
        for (var i = 0; i < text.Length; i++)
        {
            if (i > 0 && char.IsUpper(text[i]) && char.IsLower(text[i - 1])) sb.Append('-');
            sb.Append(char.ToLowerInvariant(text[i]));
        }
        return sb.ToString();
    }
}

go deeper

for a junior

Recall that [Route("api/[controller]")] uses the controller name without the Controller suffix and [action] the method name.

for a middle

Explain when tokens are replaced, how they combine with action templates, and how [[ and ]] escape literal brackets.

for a senior

Apply a slugify IOutboundParameterTransformer through RouteTokenTransformerConvention or an inline policy, and weigh tokens against literal templates on public APIs.

for a principal

Set a URL style policy, such as kebab-case and literal templates for public contracts, so refactors cannot quietly change published endpoints.

## Token replacement in attribute routes Attribute routes on controllers may contain **tokens** in square brackets. MVC replaces them while it builds the application model, before any endpoint exists: | Token | Replaced with | Example result | |---|---|---| | `[controller]` | the controller name without the `Controller` suffix | `BookSeries` | | `[action]` | the action name, normally the method name | `NewReleases` | | `[area]` | the value of the controller's `[Area]` attribute | `Admin` | ```csharp [ApiController] [Route("api/[controller]")] public class BookSeriesController : ControllerBase { [HttpGet("[action]")] // api/BookSeries/NewReleases public IActionResult NewReleases() => Ok(); [HttpGet("{id:int}")] // api/BookSeries/{id:int} public IActionResult Get(int id) => Ok(id); } ``` The docs describe it as "the last step of building the attribute routes", so the controller above behaves exactly as if you had typed the names. A few details: - Tokens also work in **route names**: `[Route("[controller]/[action]", Name = "[controller]_[action]")]` yields a unique name per action. - A base controller with `[Route("api/[controller]")]` gives every derived controller its own prefix, which is why tokens and inheritance combine well. - To match a literal `[` or `]`, double it: `[[` or `]]`. - An action template starting with `/` or `~/` is **not combined** with the controller's template. - Renaming the class or method silently changes the URL, which is the main argument against tokens on a public API. ## Parameter transformers ASP.NET Core's hook for rewriting a route value as text is `IOutboundParameterTransformer`: ```csharp public interface IOutboundParameterTransformer : IParameterPolicy { string? TransformOutbound(object? value); } ``` It is an `IParameterPolicy`, the same family as route constraints, so it can be registered by name in `RouteOptions`. The usual implementation turns PascalCase into kebab-case. There are two ways to apply it. ### 1. Attribute routes: RouteTokenTransformerConvention `RouteTokenTransformerConvention` is an `IActionModelConvention` that sets the transformer on every action, so token replacement passes the controller, action and area names through it: ```csharp builder.Services.AddControllers(options => options.Conventions.Add( new RouteTokenTransformerConvention(new SlugifyParameterTransformer()))); ``` Now `BookSeriesController.NewReleases` is served at `/api/book-series/new-releases`. Only the **token** text changes: literal text you typed and ordinary `{parameters}` are left alone. You can subclass the convention and override `ShouldApply(ActionModel)` to limit it, for instance to one area. ### 2. Conventional routes: inline in the template For `MapControllerRoute`, register the transformer under a name and use it like a constraint: ```csharp builder.Services.Configure<RouteOptions>(o => o.SetParameterPolicy<SlugifyParameterTransformer>("slugify")); app.MapControllerRoute("default", "{controller:slugify=Home}/{action:slugify=Index}/{id?}"); ``` Per the routing docs, `SubscriptionManagementController.GetAll` is then matched at `/subscription-management/get-all`, and `Url.Action("GetAll", "SubscriptionManagement")` outputs the same path. On an ordinary parameter, such as `blog/{article:slugify}`, a transformer acts only on link generation. ## Areas and inheritance Tokens compose with areas. A controller marked `[Area("Admin")]` with `[Route("[area]/[controller]/[action]")]` is served at `/Admin/BookSeries/NewReleases`, or `/admin/book-series/new-releases` once the convention is applied, because the transformer receives the area value too. A shared base class is the usual way to apply one template to every controller: ```csharp [ApiController] [Route("api/[controller]")] public abstract class BookshopControllerBase : ControllerBase { } public class AuthorsController : BookshopControllerBase { } // api/authors with slugify public class BookSeriesController : BookshopControllerBase { } // api/book-series ``` Watch for collisions after transformation: if another controller still carries a literal `[Route("api/book-series")]`, its actions and the slugified `BookSeriesController` actions can end up with the same template and HTTP method, and the conflict only surfaces as an ambiguous match at request time. ## Razor Pages and Minimal APIs - `RouteTokenTransformerConvention` **does not affect Razor Pages routes**. Pages use `PageRouteTransformerConvention`, which transforms the folder and file-name segments but not routes written in the `@page` directive. - Minimal APIs have no tokens; you write the literal path, kebab-case or not. ## What interviewers listen for - Which tokens exist and that they are replaced at startup, not per request. - The `TransformOutbound` signature and that it returns a string. - The two registration routes: the MVC convention for attribute routes, an inline name for conventional ones. - The cost of tokens: refactoring a class name changes a public URL.

  • Does RouteTokenTransformerConvention change the {id} parameter or literal text in an attribute route?
    No. It sets the transformer that token replacement uses, so only the values substituted for `[controller]`, `[action]` and `[area]` pass through it. Literal text you typed, such as `api`, and ordinary route parameters like `{id:int}` are unchanged; the parameter still matches whatever the request supplies.
  • Why might a team avoid [controller] and [action] tokens on a public API?
    Tokens tie the URL to C# names. Renaming `BookSeriesController` or an action method during a refactor changes the public path, and nothing fails at compile time. Teams with external clients often write literal templates such as `[Route("api/book-series")]` so URLs change only on purpose.

  • Says [controller] is replaced with the full class name including the Controller suffix.
  • Believes token replacement happens on every request rather than when routes are built.
  • Expects RouteTokenTransformerConvention to also rename Razor Pages routes.
  • Thinks a transformer on {id} changes which incoming values match.
  • Registers the transformer with AddSingleton and expects tokens to change.