溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

實現(xiàn)ASP.NET Core自動生成小寫破折號路由的方法

發(fā)布時間:2021-04-09 10:58:33 來源:億速云 閱讀:184 作者:啵贊 欄目:開發(fā)技術

這篇文章主要講解了“實現(xiàn)ASP.NET Core自動生成小寫破折號路由的方法”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“實現(xiàn)ASP.NET Core自動生成小寫破折號路由的方法”吧!

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

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

1、如何生成小寫的路由可以這樣設置

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

2、生成帶破折號并且小寫的路由可以這樣設置

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

似乎上面使用特性路由可以解決這個問題。但是我不想使用,因為每個action都要手動去設置,太繁瑣也很容易出錯。

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

3、解決方案

以下支持Asp.Net Core Version>=2.2

要做到這一點,首先創(chuàng)建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();
    }
}

3.1 對于Asp.Net Core2.2 MVC:

在StartUp中ConfiregeServices這樣配置

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

路由如下配置:

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這樣配置

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

路由如下配置:

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路由變?yōu)?sys/user-list

3.6 對于上面MVC項目,路由模板要調(diào)整很多,其實還可以通過實現(xiàn)IControllerModelConvention來實現(xiàn)。

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

譯者:realyrare

出處:https://www.cnblogs.com/mhg215/

感謝各位的閱讀,以上就是“實現(xiàn)ASP.NET Core自動生成小寫破折號路由的方法”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對實現(xiàn)ASP.NET Core自動生成小寫破折號路由的方法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI