Automatically generate lowercase dashed routes in ASP.NET Core

后端 未结 5 759
花落未央
花落未央 2020-12-09 09:15

ASP.NET Core uses CamelCase-Routes like http://localhost:5000/DashboardSettings/Index by default. But I want to use lowercase routes, which are delimitted by dashes: http://

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 09:57

    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,
                    "(?

    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

提交回复
热议问题