.NET Core MVC: regex routing with named groups

Routing in real life. Photo by Chris Bair on Unsplash.

Routing with regular expressions… to some the world would be a better place if everyone understood regular expressions. To others the world would be a better place without regular expressions at all. The thing is, they’re easy to create, but hard to maintain. And every language has its own take on regex.
 One of the big advantages of the .Net implementation is named groups. Today I want to show how to leverage named regular expression groups to build a routing constraint that will map each group value to a named route value.

Friendly urls

At wehkamp we use the following friendly URLs to build a SEO-friendly navigation structure:

Navigation structure for Lego Architecture

Let’s assume we need to map these routing values into a parameter object:

Introducing a regex routing constraint

Routing constraints can be used to extract routing values from a URL. We could build a single constraint for every “type” of URL. Or… we could build a more generic constraint that will take an expression and use it as a source for parsing the routing values.

Here’s our attempt:

Note: we support multiple expression just to make things more readable. What we try to do can be done by a single expression, but it won’t be very readable as it uses a lot of optional groups.

Add it to the startup

Let’s hook it up in the startup class by adding the route to the app.UseMvc:

The important part is the {*url} template. This will use a catch-all for the route. This will feed the path of the URL into the constraint (not the host nor the query-string).

Summary

Regular expressions can be very useful in mapping routing values. The .Net routing engine will do the actual mapping. In this way you can build a nice routing convention with the FromRoute decoration on parameters and / or properties.


Originally published at keestalkstech.com on February 19, 2018.