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?
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;
}