在 ASP.NET Core 版本中更新 >= 2.2
从 ASP.NET Core 2.2 开始,除了 lowercase,您还可以使用 ConstraintMap 使您的 路由虚线,这将使您的路由/Employee/EmployeeDetails/1 到 /employee/employee-details/1 而不是 /employee/employeedetails/1。
为此,首先创建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();
}
}
对于 ASP.NET Core 2.2 MVC:
在Startup 类的ConfigureServices 方法中:
services.AddRouting(option =>
{
option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
});
并且Route配置应该如下:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller:slugify}/{action:slugify}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
对于 ASP.NET Core 2.2 Web API:
在Startup类的ConfigureServices方法中:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
对于 ASP.NET Core >=3.0 MVC:
在Startup类的ConfigureServices方法中:
services.AddRouting(option =>
{
option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
});
并且Route配置应该如下:
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" });
});
对于 ASP.NET Core >=3.0 Web API:
在Startup 类的ConfigureServices 方法中:
services.AddControllers(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
});
对于 ASP.NET Core >=3.0 Razor 页面:
在Startup类的ConfigureServices方法中:
services.AddRazorPages(options =>
{
options.Conventions.Add(new PageRouteTransformerConvention(new SlugifyParameterTransformer()));
})
这将使/Employee/EmployeeDetails/1 路由到/employee/employee-details/1