Update in ASP.NET Core Version >= 2.2
From ASP.NET Core 2.2, along with lowercase you can also make your route dashed using ConstraintMap
which will make your route /Employee/EmployeeDetails/1
to /employee/employee-details/1
instead of /employee/employeedetails/1
.
To do so, first create the SlugifyParameterTransformer
class should be as follows:
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();
}
}
For ASP.NET Core 2.2 MVC:
In the ConfigureServices
method of the Startup
class:
services.AddRouting(option =>
{
option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
});
And Route configuration should be as follows:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller:slugify}/{action:slugify}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
For ASP.NET Core 2.2 Web API:
In the ConfigureServices
method of the Startup
class:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
For ASP.NET Core >=3.0 MVC:
In the ConfigureServices
method of the Startup
class:
services.AddRouting(option =>
{
option.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
});
And Route configuration should be as follows:
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" });
});
For ASP.NET Core >=3.0 Web API:
In the ConfigureServices
method of the Startup
class:
services.AddControllers(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
});
For ASP.NET Core >=3.0 Razor Pages:
In the ConfigureServices
method of the Startup
class:
services.AddRazorPages(options =>
{
options.Conventions.Add(new PageRouteTransformerConvention(new SlugifyParameterTransformer()));
})
This is will make /Employee/EmployeeDetails/1
route to /employee/employee-details/1
AddMvc()
in yourStartup.ConfigureServices()
method.AddRouting()
which is also called byAddMvc()
uses theTry
variants of the methods for adding dependencies to your service collection. So when it sees that the routing dependencies have already been added, it will skip that parts ofAddMvc()
setup logic. – Greenwell