ASP.NET Core如何自動生成小寫的破折號路由

默認狀況下,ASP.NET Core使用如 http://localhost:5000/HomeIndex 類的大駝峯路由。可是若是想使用小寫的路由,而且這些路由用破折號分隔:http://localhost:5000/home-index它們比較常見且一致。app

舉例.NET常見路由
http://localhost:5000/User/ListPages
想要的效果
http://localhost:5000/user/list-pages

一、如何生成小寫的路由能夠這樣設置

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

二、生成帶破折號而且小寫的路由能夠這樣設置

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

彷佛上面使用特性路由能夠解決這個問題。可是我不想使用,由於每一個action都要手動去設置,太繁瑣也很容易出錯。ide

我想要的效果是在程序中寫個擴展類作到可配置處理。ui

三、解決方案

如下支持Asp.Net Core Version>=2.2this

要作到這一點,首先建立SlugifyParameterTransformer類應該以下所示spa

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

3.1 對於Asp.Net Core2.2 MVC:

在StartUp中ConfiregeServices這樣配置code

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

路由以下配置:orm

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

3.2  對於Asp.Net Core2.2 Web API:

在StartUp中ConfiregeServices這樣配置blog

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

3.3 對於Asp.Net Core>=3.0 MVC:

在StartUp中ConfiregeServices這樣配置路由

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

路由以下配置:string

app.UseEndpoints(endpoints =>
{
    endpoints.MapAreaControllerRoute(
        name: "AdminAreaRoute",
        areaName: "Admin",
        pattern: "admin/{controller:slugify=Dashboard}/{action:slugify=Index}/{id:slugify?}");

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller:slugify}/{action:slugify}/{id:slugify?}",
        defaults: new { controller = "Home", action = "Index" });
});

3.4 對於Asp.Net Core>=3.0 Web API:

在StartUp中ConfiregeServices這樣配置

services.AddControllers(options => 
{
    options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
});

3.5 對於Asp.Net Core>=3.0 Razor Pages:

在StartUp中ConfiregeServices這樣配置

services.AddRazorPages(options => 
{
    options.Conventions.Add(new PageRouteTransformerConvention(new SlugifyParameterTransformer()));
});

這樣會使/Sys/UserList路由變爲/sys/user-list

3.6 對於上面MVC項目,路由模板要調整不少,其實還能夠經過實現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中ConfiregeServices這樣配置

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

譯文:https://stackoverflow.com/questions/40334515/automatically-generate-lowercase-dashed-routes-in-asp-net-core

相關文章
相關標籤/搜索