Skip to content

Instantly share code, notes, and snippets.

@yemrekeskin
Forked from RyannosaurusRex/RouteConfig.cs
Created August 26, 2014 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yemrekeskin/677fdbf319c56cdfbbbe to your computer and use it in GitHub Desktop.
Save yemrekeskin/677fdbf319c56cdfbbbe to your computer and use it in GitHub Desktop.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Sub", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "SubdomainController", action = "AnyActionYouLike", id = UrlParameter.Optional },
new { controller = new SubdomainRouteConstraint() },
new[] { "MyProjectNameSpace.Controllers" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
public class SubdomainRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
string url = httpContext.Request.Headers["HOST"];
int index = url.IndexOf(".", System.StringComparison.Ordinal);
if (index < 0)
{
return false;
}
//This will bi not enough in real web. Because the domain names will end with ".com",".net"
//so probably there will be a "." in url.So check if the sub is not "yourdomainname" or "www" at runtime.
string sub = url.Split('.')[0];
if (sub == "www" || sub == "yourdomainname" || sub == "mail")
{
return false;
}
//Add a custom parameter named "user". Anythink you like :)
values.Add("subdomainAsAParameter", sub);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment