5-Minute Implementation of a Twitter-esque Profiles URL Pattern  in Asp.Net Core

5-Minute Implementation of a Twitter-esque Profiles URL Pattern in Asp.Net Core

While no longer in use by Twitter itself, Twitter popularized a very popular URL format for user profiles where to visit anyone's profile, you simply go to twitter.com/@username. This works great as it limits the risk of URL conflicts while giving every user an easy to remember short profile URL. In Asp.net core it's actually very simple to implement and relies on two often overlooked features of Asp.Net Core routes, Regex based routing and named parameters defined at a controller level (i.e. It will be available as a parameter to all methods in the controller class without specifying it directly in the methods own route attribute).

In this post, I give a very quick run through on how to implement it in Asp.Net Core 3.1, however everything you need to know is in the route attribute of the ProfilesController in the sample project which can be can be found at https://github.com/moodio/netcoreprofileurls

To get started, create a Asp.Net Core API web application. I use Visual Studio but you can use your IDE of choice. Then create a new controller, name it  ProfilesController or anything else you choose, doesn't really matter.

Next, in the Route attribute of the controller, change the string pattern from [Route("[controller]")] to [Route("{profile:regex(^[[@]]{{1}}[[0-9a-zA-Z]]+$)}")] (or modify it based on the profile pattern you want). The pattern i chose will match a string consisting of an @ symbol followed by any combination of alphanumeric characters.

Note: By default Asp.Net Core uses ignore-case and cultural invariant regex matching options.

NOTE: There are two things to note about the pattern, first, profile is the name of the attribute that will be injected into the methods and what the parameter names should match, and second, that the pattern needs to be escaped in a slightly different way to regular C# strings, where opening brackets and parentheses need to be typed twice instead of once. i.e We change [@]{1} to [[@]]{{1}}

And finally, to get the value of profile within a route, we add it as an parameter

And now you have a twitter-esque routing pattern in Asp.Net Core that takes less than 5 minutes to implement.

And here are our results:

To implement this in a production service, it is of course advised to add additional safe guards, such as timeout limits.

Mahmoud Swehli

Mahmoud Swehli

Founder of Moodio

London, UK