Search code examples
asp.net-coreasp.net-core-routingasp.net-core-2.2

The constraint reference 'slugify' could not be resolved to a type


ASP.NET Core 2.2 has introduced an option for slugifying routing url using Parameter transformer as follows:

routes.MapRoute(
    name: "default",
    template: "{controller=Home:slugify}/{action=Index:slugify}/{id?}");

I have done the same thing as follows:

routes.MapRoute(
    name: "default",
    template: "{controller:slugify}/{action:slugify}/{id?}",
    defaults: new { controller = "Home", action = "Index" });

My routing configuration in the ConfigureServices method as follows:

services.AddRouting(option =>
            {
                option.LowercaseUrls = true;
            });

but getting the following errors:

InvalidOperationException: The constraint reference 'slugify' could not be resolved to a type. Register the constraint type with 'Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap'.

and

RouteCreationException: An error occurred while creating the route with name 'default' and template '{controller:slugify}/{action:slugify}/{id?}'.

May be I am missing anything more! Any help please!


Solution

  • As ASP.NET Core Documentation says I have to configure Parameter transformer using ConstraintMap. So I have done as follows and it works:

    Routing configuration in the ConfigureServices method should be as follows:

    services.AddRouting(option =>
                {
                    option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
                    option.LowercaseUrls = true;
                });
    

    Then the SlugifyParameterTransformer as follows:

    public class SlugifyParameterTransformer : IOutboundParameterTransformer
        {
            public string TransformOutbound(object value)
            {
                // Slugify value
                return value == null ? null : Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower();
            }
        }
    

    Thank you.