Search code examples
c#restasp.net-core.net-core

How to globally configure ASP.NET Core 6+ API routes to be formatted as kebab-case when generated from controller names?


I have an ASP.NET Core 6 Web API project. Some of the endpoints are related to controllers whose names consist of multiple words and thus are in PascalCase format as per the convention in .NET. Suppose I have a PackageGroupsController. I'd like its route to be /package-groups instead of the default /PackageGroups and I don't want to specify a hardcoded route for each controller. How can I achieve that using a global configuration or something?


Solution

  • AddControllers allows you to customize conventions used, you can try using those with RouteTokenTransformerConvention. Something like:

    builder.Services.AddControllers(opts => 
        opts.Conventions.Add(new RouteTokenTransformerConvention(new ToKebabParameterTransformer())));
    
    public class ToKebabParameterTransformer : IOutboundParameterTransformer
    {
        public string TransformOutbound(object? value) => value != null 
            ? Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower() // to kebab 
            : null; 
    }