Hi Folks! In this post I will run through an issue I had with the BlogEngine and how I used ASP.NET MVC routing with constraints to solve it.

Although this website uses the core of the CMS platform along with MVC as a different front-end, the same can be applied with the official version, which is built using ASP.NET WebForms. Routing is also a feature of WebForms.

This website contains a controller called PostsController that basically takes care of bringing the details of several articles and rendering them properly. If you take a look at the URL bar from your browser, you will see something like this: guilhermesuzuki.com/[guid]. Normally, MVC would try to find a controller with a name similar to a GUID...

BlogEngine.NET uses GUIDs as primary key for posts and other entities, so I decided to use them instead of slugs or incremental numbers. GUIDs are structured in a way that we could use constraints with routing in MVC to create smarter URLs.

Take a look at the code above: the PostsController has an action called Details that renders all information about a particular post, (again) using GUIDs as indexes. But the default MVC route would be http://guilhermesuzuki.com/posts/details/{guid}, kind of a long URL for something so simple as a link to a post. I wanted to simplify the URLs, making them accessible directly by http://guilhermesuzuki/article/[guid].

Later on the idea went further and I decided to simplify the URLs even more, making them accessible directly by their GUIDs.

So, I created a top priority route in my RouteConfig file using a regular expression to validate the string id parameter. And then setting the route default to the controller and Details action.

What's cool about it is that the default route still works for older URLs, so there was no need to update the previous references to the Posts/Details/{guid} paths I used in videos before and what not.

Even the controller actions inside the web application didn't have to be changed at all, because MVC uses a reverse technique to determine if there is a suitable route from that mentioned action.

If the front-end was based on slugs for that, like the way the official version works, it would be very hard to determine a shortcut for the custom route.

Slugs are based on post titles with spaces replaced by single dash.

Well, I hope this use case was useful for the readers and a quick example of routing with ASP.NET MVC and constraints.