When I set out to create this site, I didn’t just want one blog. I wanted a framework where each of my areas of interest — privacy, projects, code, and more — could live on its own dedicated subweb.
Each subweb needed its own routes (for home, categories, posts, and sitemaps) but I didn’t want to copy and paste files or spin up a new codebase every time. Instead, I wanted a single MVC application that could serve any number of subwebs dynamically, with nothing more than a database entry.
The Challenge
ASP.NET MVC’s routing system is flexible, but by default it expects you to define routes in RouteConfig.cs
manually. That’s fine for one site, but not for a dozen subwebs that each need their own routing.
I needed a way to generate routes dynamically from the database so that when I add a new interest area, the site just works — no extra files or hardcoded routes.
The Solution
I built a custom SubdomainRoute
class and tied it into RouteConfig
. On startup, the app queries the database for interest areas, loops through them, and registers a set of routes for each subdomain. Here’s the heart of the system:
// Inside RouteConfig.cs
foreach (InterestArea InterestAreaFound in _DbInterestAreaContext.InterestAreas)
{
SubdomainTitle = InterestAreaFound.Title;
ControllerName = SubdomainTitle.Replace("-", String.Empty);
routes.Add(
new SubdomainRoute(SubdomainTitle, new { controller = ControllerName, action = "index", id = UrlParameter.Optional })
);
routes.Add(
new SubdomainRoute(SubdomainTitle, new { controller = ControllerName, action = "category", category = UrlParameter.Optional })
);
routes.Add(
new SubdomainRoute(SubdomainTitle, new { controller = ControllerName, action = "post", title = UrlParameter.Optional })
);
routes.Add(
new SubdomainRoute(SubdomainTitle, new { controller = ControllerName, action = "sitemap", title = UrlParameter.Optional })
);
}
This code automatically wires up every subdomain I’ve defined in the database. No extra controllers or views per subweb — just one codebase serving them all.
The Custom Route
The real engine is SubdomainRoute
, which inspects the incoming request’s host, compares it to the database entry, and decides if it matches. If it does, it maps the route to the correct controller and action.
That means projects.justingengo.com
and code.justingengo.com
can both resolve correctly, and if I add another tomorrow, it works with no extra code.
Why This Matters
- Single codebase: Everything is maintained in one place.
- Database-driven: Adding a new subweb is as easy as adding a row.
- Scalable: No messy duplicate controllers or config files.
What’s Next
This is just the start. In future posts, I’ll go deeper into how content gets entered (via my mini-CMS), how categories and posts are handled, and how sitemaps are generated automatically for each subweb.
For now, the big takeaway is this: with a bit of custom route logic, one .NET MVC application can run many independent subwebs — cleanly and flexibly.