水果电子商务网站建设规划书,怎么做区块链网站,无锡做网站要多少钱,滁州市公共资源交易中心ASP.NET CORE MVC 中#xff0c;默认的 Route 模板是#xff1a; /{controller}/{action} 。我们可以通过开启 URL 小写转换将 URL 变为小写#xff0c;但此方式在 Controller 或者 Action 为一个词组时#xff0c;生成的 URL 并不友好。假设我们有 UserController 和 Add… ASP.NET CORE MVC 中默认的 Route 模板是 /{controller}/{action} 。我们可以通过开启 URL 小写转换将 URL 变为小写但此方式在 Controller 或者 Action 为一个词组时生成的 URL 并不友好。假设我们有 UserController 和 AddUser 方法则框架生成的 URL 可能是 /User/AddUser 在开启小写转换的情况下可能是下面的结果 /user/adduser 。包含大写字符的 URL 并没有问题但是小写的 URL 更加常规而完全转换小写造成的问题就是 URL 的可读性很差。本文将提供一些代码帮助框架生成减号分隔样式的 URL 当应用了这些代码以后生成的 URL 类似这样 /user/add-user 。微软为我们提供了 RouteAttribute 可以对 Controller 或者 Action 进行标记以达到自定义访问路径的目的。这种方式非常强大但在项目较大的情况下使用起来有些繁杂。毕竟手工对每一个 Controller 和 Action 进行标记也有不小的工作量。ASP.NET CORE MVC 框架中定义了一个 IControllerModelConvention 接口我们可以实现该接口在运行时为 Action 附加一个 Route 模型。在项目中新建 DashedRoutingConvention 类文件代码如下 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 parts new Liststring(); foreach (var attr in controller.Attributes) { if (attr is AreaAttribute area) { parts.Add(area.RouteValue); } } if ( parts.Count 0 controller.ControllerName Home controllerAction.ActionName Index ) { continue; } parts.Add(PascalToKebabCase(controller.ControllerName)); if (controllerAction.ActionName ! Index) { parts.Add(PascalToKebabCase(controllerAction.ActionName)); } selector.AttributeRouteModel new AttributeRouteModel { Template string.Join(/, parts) }; } } } private 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(); } }之后将 DashedRoutingConvention 在 Startup.cs 中注册。public void ConfigureServices(IServiceCollection services){ // Add framework services. services.AddMvc(options options.Conventions.Add(new DashedRoutingConvention()));}至此全部代码完毕。Notices本代码支持 Area 并会对 Area 名称也进行转义。本代码使用自定义路由的方式实现功能所以可能对预定义路由有影响。更多与路由相关的信息可参见https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing本代码参考了其他代码详见https://stackoverflow.com/questions/40334515/automatically-generate-lowercase-dashed-routes-in-asp-net-core码农很忙授权中心已经启用了本代码演示https://passport.coderbusy.com/原文https://www.coderbusy.com/archives/956.html.NET社区新闻深度好文欢迎访问公众号文章汇总 http://www.csharpkit.com