Automatically generate lowercase dashed routes in ASP.NET Core

倾然丶 夕夏残阳落幕 提交于 2019-11-30 08:34:33
Oliver

A little late to the party here but.. Can do this by implementing IControllerModelConvention.

 public class DashedRoutingConvention : IControllerModelConvention
 {
        public void Apply(ControllerModel controller)
        {
            var hasRouteAttributes = controller.Selectors.Any(selector =>
                                               selector.AttributeRouteModel != null);
            if (hasRouteAttributes)
            {
                // This controller manually defined some routes, so treat this 
                // as an override and not apply the convention here.
                return;
            }

            foreach (var controllerAction in controller.Actions)
            {
                foreach (var selector in controllerAction.Selectors.Where(x => x.AttributeRouteModel == null))
                {
                    var template = new StringBuilder();

                    if (controllerAction.Controller.ControllerName != "Home")
                    {
                        template.Append(PascalToKebabCase(controller.ControllerName));
                    }

                    if (controllerAction.ActionName != "Index")
                    {
                        template.Append("/" + PascalToKebabCase(controllerAction.ActionName));
                    }

                    selector.AttributeRouteModel = new AttributeRouteModel()
                    {
                        Template = template.ToString()
                    };
                }
            }
        }

        public static string PascalToKebabCase(string value)
        {
            if (string.IsNullOrEmpty(value))
                return value;

            return Regex.Replace(
                value,
                "(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])",
                "-$1",
                RegexOptions.Compiled)
                .Trim()
                .ToLower();
        }
}

Then registering it in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc(options => options.Conventions.Add(new DashedRoutingConvention()));
}

Can find more info and example here https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing

I'm using Asp.NetCore 2.0.0 and Razor Pages (no explicit controller necessary), so all that's needed is:

  1. Enable Lowercase Urls:

    services.AddRouting(options => options.LowercaseUrls = true);

  2. Create a file named Dashboard-Settings.cshtml and the resulting route becomes /dashboard-settings

Copied from ASP.NET Core 2.2 documentation:

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

public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
    public string TransformOutbound(object value)
    {
        if (value == null) { return null; }

        // Slugify value
        return Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower();
    }
}

Update in ASP.NET Core 2.2

In the ConfigureServices method of the Startup class:

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

And the 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();
    }
}

And route configuration should be as follows:

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

This is will make /Employee/EmployeeDetails/1 route to /employee/employee-details/1

Thanks for the information, however it's better to filter the selectors, in order to skip those with a custom route template : [HttpGet("/[controller]/{id}")] for example)

foreach (var selector in controllerAction.Selectors
                                         .Where(x => x.AttributeRouteModel == null))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!