这篇文章主要讲解了“实现ASP.NET Core自动生成小写破折号路由的方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“实现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
services.ConfigureRouting(setupAction => {
setupAction.LowercaseUrls = true;
});
[Route("dashboard-settings")]
class DashboardSettings:Controller {
public IActionResult Index() {
// ...
}
}
似乎上面使用特性路由可以解决这个问题。但是我不想使用,因为每个action都要手动去设置,太繁琐也很容易出错。
我想要的效果是在程序中写个扩展类做到可配置处理。
以下支持Asp.Net Core Version>=2.2
要做到这一点,首先创建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();
}
}
在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" });
});
在StartUp中ConfiregeServices这样配置
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
在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" });
});
在StartUp中ConfiregeServices这样配置
services.AddControllers(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
});
在StartUp中ConfiregeServices这样配置
services.AddRazorPages(options =>
{
options.Conventions.Add(new PageRouteTransformerConvention(new SlugifyParameterTransformer()));
});
这样会使/Sys/UserList路由变为/sys/user-list
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/
感谢各位的阅读,以上就是“实现ASP.NET Core自动生成小写破折号路由的方法”的内容了,经过本文的学习后,相信大家对实现ASP.NET Core自动生成小写破折号路由的方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。