我是靠谱客的博主 含糊荷花,这篇文章主要介绍ASP.NET Core自动生成小写破折号路由的实现方法,现在分享给大家,希望可以做个参考。

默认情况下,ASP.NET Core使用如 http://localhost:5000/HomeIndex 类的大驼峰路由。但是如果想使用小写的路由,并且这些路由用破折号分隔:http://localhost:5000/home-index它们比较常见且一致。

复制代码
1
2
3
4
举例.NET常见路由 http://localhost:5000/User/ListPages 想要的效果 http://localhost:5000/user/list-pages

1、如何生成小写的路由可以这样设置

复制代码
1
2
3
services.ConfigureRouting(setupAction => { setupAction.LowercaseUrls = true; });

2、生成带破折号并且小写的路由可以这样设置

复制代码
1
2
3
4
5
6
[Route("dashboard-settings")] class DashboardSettings:Controller { public IActionResult Index() { // ... } }

似乎上面使用特性路由可以解决这个问题。但是我不想使用,因为每个action都要手动去设置,太繁琐也很容易出错。

我想要的效果是在程序中写个扩展类做到可配置处理。

3、解决方案

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

要做到这一点,首先创建SlugifyParameterTransformer类应该如下所示

复制代码
1
2
3
4
5
6
7
8
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这样配置

复制代码
1
2
3
4
services.AddRouting(option => { option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer); });

路由如下配置:

复制代码
1
2
3
4
5
6
7
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这样配置

复制代码
1
2
3
4
5
6
7
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这样配置

复制代码
1
2
3
4
services.AddRouting(option => { option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer); });

路由如下配置:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
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这样配置

复制代码
1
2
3
4
services.AddControllers(options => { options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer())); });

3.5 对于Asp.Net Core>=3.0 Razor Pages:

在StartUp中ConfiregeServices这样配置

复制代码
1
2
3
4
services.AddRazorPages(options => { options.Conventions.Add(new PageRouteTransformerConvention(new SlugifyParameterTransformer())); });

这样会使/Sys/UserList路由变为/sys/user-list

3.6 对于上面MVC项目,路由模板要调整很多,其实还可以通过实现IControllerModelConvention来实现。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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这样配置

复制代码
1
2
3
4
5
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/

以上就是ASP.NET Core自动生成小写破折号路由的实现方法的详细内容,更多关于ASP.NET Core生成小写破折号路由的资料请关注靠谱客其它相关文章!

最后

以上就是含糊荷花最近收集整理的关于ASP.NET Core自动生成小写破折号路由的实现方法的全部内容,更多相关ASP.NET内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(111)

评论列表共有 0 条评论

立即
投稿
返回
顶部