SteinTech
SteinTech

Reputation: 4068

Can't slugify routed url's in asp.net core mvc

I'm trying to slugify some routed url's. I followed this article, but I can't replicate the result. When setting a breakpoint in TransformOutbound() it never hits, so I guess the transformer never gets called for some reason.

SlugifyParameterTransformer:

public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
    public string TransformOutbound(object value)
    {
        string result = default;

        if (!value.IsNull())
        {
            result = Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower();
        }

        return result;
    }
}

Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLCAssets(opt => 
        {
            opt.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
        });
}

AddLCAssets:

public static IServiceCollection AddLCAssets(this IServiceCollection services, Action<MvcOptions> options = default)
{
    if (options != default)
    {
        services.AddMvc(options)
            .SetCompatibilityVersion(Const.DefaultCompatibilityVersion);
    }
    else
    {
        services.AddMvc()
            .SetCompatibilityVersion(Const.DefaultCompatibilityVersion);
    }

    return services;
}

Upvotes: 1

Views: 1061

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32069

First your SlugifyParameterTransformer class should be 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();
    }
}

Then in the Startup.ConfigureServices as follows:

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

Then your route configuration in Startup.Configure should be as follows:

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

The above settings will make /Employee/EmployeeDetails/1 route to /employee/employee-details/1

Upvotes: 2

Related Questions