C# / .NETDevOpsMisc
C# / .NET
Domain Routes and using subdomains in MVC as routes
Alexandru Puiu
Alexandru Puiu
September 24, 2012
1 min

I came across this when trying to build a website that takes advantage of sub domains in a MVC project. You can route subdomains in MVC to a particular controller, and specific actions.

In order to do this, you must make your website listen directly on the IP Address, and point a wildcard A record for all subdomains. In IIS 7, under Bindings, add a binding for http or https, set the IP to the dedicated IP for the site, and leave the Host name empty.

In your DNS Server (GoDaddy or Windows DNS Server), add the following A records

Host: @ or (same as parent)
IP address: (your dedicated IP)
Host: *
IP address: (your dedicated IP)
NOTE: Not all DNS Servers have wildcard options

This will make your website listen for any subdomains on your site.

Reference the classes attached below, and add the following routes to your project

_routes.Add("BlogRouteProfile", new DomainRoute("{url}.example.com", "", new { controller = "Blog", action = "ViewBlog", url = "" }));
_routes.Add("BlogLatestPosts", new DomainRoute("{url}.example.com", "latest-posts", new { controller = "Blog", action = "BlogLatestPosts", url = "" }));
_routes.Add("BlogPost1", new DomainRoute("{url}.example.com", "rss", new { controller = "Blog", action = "BlogRss", url = "" }));
_routes.Add("BlogPost3", new DomainRoute("{url}.example.com", "pages/{pageName}", new { controller = "Blog", action = "BlogPageView", url = "" }));

In your controller, you can now define Actions, just as you normally would for a regular route.

public class BlogController : Controller
{
    public ActionResult BlogPageView(string url, string pageName)
    {
        return View();
    }
}

Tags

utils
Alexandru Puiu

Alexandru Puiu

Engineer / Security Architect

Systems Engineering advocate, Software Engineer, Security Architect / Researcher, SQL/NoSQL DBA, and Certified Scrum Master with a passion for Distributed Systems, AI and IoT..

Expertise

.NET
RavenDB
Kubernetes

Social Media

githubtwitterwebsite

Related Posts

RavenDB Integration Testing
Using RavenDB in Integration Testing
December 24, 2022
2 min

Subscribe To My Newsletter

I'll only send worthwhile content I think you'll want, less than once a month, and promise to never spam or sell your information!
© 2023, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media