I was presented with a challenge recently. Six different types of pages wanted to appear after a generic sub directory.

Well that's fine. In MVC, you can just set up six different routes to cope with the six different types of pages. Each of those routes can have a different default controller and action. Job done.

  • Type 1 - type/{slug}
  • Type 2 - type/{type1}/{slug}
  • Type 3 - type/{type1}/{type2}/{slug}
  • etc...

Only it was not as straight forward as that. These different types of pages would fall under the same route pattern, so it wasn't just a case of creating different routes. So I would have to create one route (say type/{slug}), and direct all these type of pages under the same route.

But each of these types of pages would need to fall under a different controller and action. How to cope with that?

In MVC, you can create a constraint against a route. The constraint acts as the meat between a route being found, based on the pattern of the URL, and being directed to the appropriate controller and action.

In older versions of MVC (well certainly MVC4), you could use the constraint to override the "controller" and "action" properties in the Microsoft.AspNetCore.Routing.

I'm not sure if that's what constraints were really designed for, but hey it worked! In MVC4 anyways, but not for ASP.NET Core it would seem.

So I had to come up with a way of making it work in ASP.NET Core.

Thanks to the fact that ASP.NET Core is open source and freely available on GitHub, I managed to load up the class that holds the route, and the solution is to create your own Route which would inherit from Microsoft.AspNetCore.Routing.Route. It seems that the Controller and Action are set in the RouteAsync function, so it was the case of overriding that.

I had to recreate the code that creates the RouteValueDictionary (inside RouteAsync) and then being able to set the controller and action before calling the base RouteAsync function.

After that, it's a case of registering the routes under your newly created Route class, rather than the one that comes with ASP.NET Core.

If you ever come up with a challenge like that, just remember that ASP.NET Core is open sourced and freely available on GitHub. You can look and see how a particular area functions and operates.

About Dave

I am a .NET developer, building web applications in .NET Framework and .NET Core with a SQL Server database.

Some of the .NET packages I have used include Entity Framework and MVC.

I've also used many JavaScript frameworks such as React and jQuery, and have experience building CSS in SASS.

Related Articles

Related Tags