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

ε祈祈猫儿з 提交于 2020-01-02 12:01:53

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/52922418/the-constraint-reference-slugify-could-not-be-resolved-to-a-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!