Dynamic Routing In ASP.NET Web API

What is dynamic routing?

The purpose of dynamic routing is to produce pretty, intuitive URLs on your website that help improve SEO and make your application look more professional.

For example, if I own the site ferrets.com and have a database of the different breeds of ferrets, I could use dynamic routing to produce URLs like ferrets.com/albino or ferrets.com/black-sable. If the user enters a breed of ferret in the URL that doesn’t exist, like ferrets.com/doberman-pinscher, a 404 not found response should be shown returned.

An example using .NET Web API and C#

Here you can see the proof of dynamic routing, given the URL /ferret/albino, some data is returned.

Where a 404 not found is returned when an invalid URL slug is used.

The Code

I will be using some hard coded values of ferret breeds, instead of a database for this example.

var mockDatabase = new List<FerretModel>
{
	new FerretModel
	{
		Name = "Black Sable",
		Slug = "black-sable",
	},
	new FerretModel
	{
		Name = "Albino",
		Slug = "albino"
	},
};

The controller action takes a route with a parameter value, that represents the requested ferret breed slug.

public class FerretController : ApiController
{
	[Route("ferret/{breedSlug}")]
	public FerretModel GetBySlug(string breedSlug)
	{ ...

Then we check our “database” to see if the slug exists, and either return the data or throw a 404 if not found.

//check if the passed in slug exists in our database
var ferret = mockDatabase.FirstOrDefault(f => string.Equals(breedSlug, f.Slug, StringComparison.InvariantCultureIgnoreCase));

//throw 404 if not found in database
if (ferret == null)
{
	throw new HttpResponseException(HttpStatusCode.NotFound);
}

return ferret;

You can download the .NET solution for this simple example here.

Leave a Reply

Your email address will not be published. Required fields are marked *