Skip to content

Instantly share code, notes, and snippets.

@bjcull
Created February 18, 2015 10:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save bjcull/6d1156df428447caf43d to your computer and use it in GitHub Desktop.
Save bjcull/6d1156df428447caf43d to your computer and use it in GitHub Desktop.
A class to detect the subdomain and pass it through as a route parameter
public class SubdomainRoute : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
if (httpContext.Request == null || httpContext.Request.Url == null)
{
return null;
}
var host = httpContext.Request.Url.Host;
var index = host.IndexOf(".");
string[] segments = httpContext.Request.Url.PathAndQuery.TrimStart('/').Split('/');
if (index < 0)
{
return null;
}
var subdomain = host.Substring(0, index);
string[] blacklist = { "www", "yourdomain", "mail" };
if (blacklist.Contains(subdomain))
{
return null;
}
string controller = (segments.Length > 0) ? segments[0] : "Home";
string action = (segments.Length > 1) ? segments[1] : "Index";
var routeData = new RouteData(this, new MvcRouteHandler());
routeData.Values.Add("controller", controller); //Goes to the relevant Controller class
routeData.Values.Add("action", action); //Goes to the relevant action method on the specified Controller
routeData.Values.Add("subdomain", subdomain); //pass subdomain as argument to action method
return routeData;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
//Implement your formating Url formating here
return null;
}
}
@simonpbond
Copy link

I was reading your blog, and found the post related to this code very interesting.

However, I'm curious as to how I use it with vNext (MVC6) as it doesn't seem to work for me.
Excuse my ignorance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment