在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)
{
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);
});
并且路由配置应如下:
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);
});
并且路由配置应如下:
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
AddMvc()
你的Startup.ConfigureServices()
方法。AddRouting()
也可以AddMvc()
使用Try
方法的变体来调用该方法,以将依赖项添加到服务集合中。因此,当看到路由依赖性已经添加时,它将跳过AddMvc()
设置逻辑的那部分。