更新 ASP.NET Core 版本 >= 2.2
从ASP.NET Core 2.2开始,您还可以使用小写字母将您的路由设为虚线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:
在类的ConfigureServices
方法中Startup
:
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:
在类的ConfigureServices
方法中Startup
:
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:
在类的ConfigureServices
方法中Startup
:
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:
在类的ConfigureServices
方法中Startup
:
services.AddControllers(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
});
对于 ASP.NET Core >=3.0 Razor 页面:
在类的ConfigureServices
方法中Startup
:
services.AddRazorPages(options =>
{
options.Conventions.Add(new PageRouteTransformerConvention(new SlugifyParameterTransformer()));
})
这将使/Employee/EmployeeDetails/1
路线/employee/employee-details/1