Skip to content

Instantly share code, notes, and snippets.

@solrevdev
Forked from bjcull/SubdomainRoute.cs
Created August 5, 2016 14:41
Show Gist options
  • Select an option

  • Save solrevdev/ea365dc39778e40681175731f147f833 to your computer and use it in GitHub Desktop.

Select an option

Save solrevdev/ea365dc39778e40681175731f147f833 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment