在ASP.NET Core中自动生成小写虚线路径

时间:2016-10-30 22:51:59

标签: url routing asp.net-core asp.net-core-mvc

ASP.NET Core默认使用像http://localhost:5000/DashboardSettings/Index这样的CamelCase-Routes。但我想使用由破折号分隔的小写路由:http://localhost:5000/dashboard-settings/index它们更常见且更一致,因为我的应用程序扩展了一个运行Wordpress的网站,该网站还有带破折号的小写网址。

我了解到我可以使用路由选项将网址更改为小写:

services.ConfigureRouting(setupAction => {
    setupAction.LowercaseUrls = true;
});

这有效,但给了我的网址没有任何像http://localhost:5000/dashboardsettings/index这样的分隔符,这些分隔符很难读。我可以使用路径属性来定义自定义路由,如

[Route("dashboard-settings")]
class DashboardSettings:Controller {
    public IActionResult Index() {
        // ...
    }
}

但这会导致额外工作并且容易出错。我更喜欢一个自动解决方案,它搜索大写字符,在它们之前插入一个破折号并使大写字母小写。对于旧的ASP.NET来说,这不是一个大问题,但在ASP.NET Core上,我看不到如何处理这个问题的方向。

这是怎么做到这里的?我需要某种接口,我可以生成url(比如标记帮助器),并用dash-delimiters替换CamelCase。然后我需要另一种接口用于路由,以便将破折号分隔符URL转换回CamelCase,以便与我的控制器/动作名称正确匹配。

5 个答案:

答案 0 :(得分:12)

派对有点晚了但是.. 可以通过实现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();
        }
}

然后在Startup.cs中注册

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

可以在https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing

找到更多信息和示例

答案 1 :(得分:8)

我正在使用Asp.NetCore 2.0.0和Razor Pages(不需要显式控制器),所以只需要:

  1. 启用小写网址:

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

  2. 创建名为Dashboard-Settings.cshtml的文件,生成的路由变为/dashboard-settings

答案 2 :(得分:2)

在ASP.NET Core 2.2中更新

ConfigureServices类的Startup方法中:

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

SlugifyParameterTransformer类应如下所示:

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

并且路由配置应如下:

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

这将使/Employee/EmployeeDetails/1到达/employee/employee-details/1

答案 3 :(得分:2)

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

答案 4 :(得分:0)

感谢您提供相关信息,但是最好过滤选择器,以便跳过那些使用自定义路由模板的信息:例如[HttpGet("/[controller]/{id}")]

foreach (var selector in controllerAction.Selectors
                                         .Where(x => x.AttributeRouteModel == null))