Asp.Net Core 3 Routing Constraints

Asp.Net Core 3 made a lot of changes, many for performance reasons and others for logical reasons. One of those changes has to do with routing. While I won't dive into all the specifics, I will give you a working example of how to use the new routing to create something like you would want for a public facing website.

When you first create a new MVC project, your Startup.cs will containt something like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { ... app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); }

You don't normally want /Home/ in all of your urls, and you definitely don't want your site (for SEO reasons), responding to '/about-us' and '/Home/about-us'. To solve this we want to add a new rule just for the home controller, then have the default rule handle everything except the home controller:

endpoints.MapControllerRoute( name: "home", pattern: "{action=Index}/{id?}", defaults: new { controller = "Home" }); endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}", null, constraints: new { controller = new RegexRouteConstraint(new Regex("^(?!home)$", RegexOptions.IgnoreCase))});

The first route mapping pattern only has an action and an optional id, and then we add the default controller of home separately, so it isn't required in the URL. Then in the default rule, we add a constraint to prevent it from matching "home". As you can see, I accomplished this with a regular expression and a negative lookahead. If one desired, they could also implement their own IRouteConstraint and use that instead.

Read More