ASP.NET Core自動(dòng)生成小寫破折號(hào)路由的實(shí)現(xiàn)方法
默認(rèn)情況下,ASP.NET Core使用如 http://localhost:5000/HomeIndex 類的大駝峰路由。但是如果想使用小寫的路由,并且這些路由用破折號(hào)分隔:http://localhost:5000/home-index它們比較常見且一致。
舉例.NET常見路由 http://localhost:5000/User/ListPages 想要的效果 http://localhost:5000/user/list-pages
1、如何生成小寫的路由可以這樣設(shè)置
services.ConfigureRouting(setupAction => { setupAction.LowercaseUrls = true; });
2、生成帶破折號(hào)并且小寫的路由可以這樣設(shè)置
[Route("dashboard-settings")] class DashboardSettings:Controller { public IActionResult Index() { // ... } }
似乎上面使用特性路由可以解決這個(gè)問題。但是我不想使用,因?yàn)槊總€(gè)action都要手動(dòng)去設(shè)置,太繁瑣也很容易出錯(cuò)。
我想要的效果是在程序中寫個(gè)擴(kuò)展類做到可配置處理。
3、解決方案
以下支持Asp.Net Core Version>=2.2
要做到這一點(diǎn),首先創(chuàng)建SlugifyParameterTransformer類應(yīng)該如下所示
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 對(duì)于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 對(duì)于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 對(duì)于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 對(duì)于Asp.Net Core>=3.0 Web API:
在StartUp中ConfiregeServices這樣配置
services.AddControllers(options => { options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer())); });
3.5 對(duì)于Asp.Net Core>=3.0 Razor Pages:
在StartUp中ConfiregeServices這樣配置
services.AddRazorPages(options => { options.Conventions.Add(new PageRouteTransformerConvention(new SlugifyParameterTransformer())); });
這樣會(huì)使/Sys/UserList路由變?yōu)?sys/user-list
3.6 對(duì)于上面MVC項(xiàng)目,路由模板要調(diào)整很多,其實(shí)還可以通過實(shí)現(xiàn)IControllerModelConvention來實(shí)現(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())); }
譯者:realyrare
以上就是ASP.NET Core自動(dòng)生成小寫破折號(hào)路由的實(shí)現(xiàn)方法的詳細(xì)內(nèi)容,更多關(guān)于ASP.NET Core生成小寫破折號(hào)路由的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- ASP.NET?Core使用EF創(chuàng)建模型(包含屬性、排除屬性、主鍵和生成值)
- ASP.NET Core 5中如何生成PDF文檔
- Asp.Net Core使用swagger生成api文檔的完整步驟
- 詳解ASP.NET Core 2.0 路由引擎之網(wǎng)址生成(譯)
- Asp.NetCore1.1版本去掉project.json后如何打包生成跨平臺(tái)包
- Asp.net core WebApi 使用Swagger生成幫助頁實(shí)例
- 基于ASP.NET Core數(shù)據(jù)保護(hù)生成驗(yàn)證token示例
- asp.net core實(shí)現(xiàn)在線生成多個(gè)文件將多個(gè)文件打包為zip返回的操作
相關(guān)文章
ASP.NET中Validation驗(yàn)證控件正則表達(dá)式特殊符號(hào)的說明
本文介紹asp.net中RegularExpressionValidator控件中的幾種特殊字符串使用規(guī)則,并做了代碼演示,希望對(duì)大家有所幫助。2016-04-04對(duì)ASP.Net的WebAPI項(xiàng)目進(jìn)行測(cè)試
這篇文章介紹了對(duì)WebAPI項(xiàng)目進(jìn)行測(cè)試的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04asp.net調(diào)用系統(tǒng)設(shè)置字體文本框的方法
這篇文章主要介紹了asp.net調(diào)用系統(tǒng)設(shè)置字體文本框的方法,包括設(shè)置文本字體樣式和大小,需要的朋友可以參考下2014-09-09C#頁碼導(dǎo)航顯示及算法實(shí)現(xiàn)代碼
C#頁碼導(dǎo)航算法要求:頁數(shù)小于等于1時(shí)不顯示;頁數(shù)大于10時(shí),自動(dòng)縮短,需要的朋友可以了解下2012-12-12Asp.Net Core 調(diào)用第三方Open API查詢物流數(shù)據(jù)的示例
這篇文章主要介紹了Asp.Net Core 調(diào)用第三方Open API查詢物流數(shù)據(jù)的示例,幫助大家更好的理解和學(xué)習(xí)使用Asp.Net Core,感興趣的朋友可以了解下2021-03-03