Skip to content

Instantly share code, notes, and snippets.

@RyannosaurusRex
Last active January 19, 2018 02:18
Show Gist options
  • Save RyannosaurusRex/4145948 to your computer and use it in GitHub Desktop.
Save RyannosaurusRex/4145948 to your computer and use it in GitHub Desktop.
ASP.NET MVC Subdomain Routing
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;
}
string sub = url.Split('.')[0];
if (sub == "www" || sub == "yourdomainname" || sub == "mail" /* || sub = "some-blacklist-subdomain" */)
{
return false;
}
//Add a custom parameter named "user". Anythink you like :)
values.Add("subdomainAsAParameter", sub);
return true;
}
}
@IDisposable
Copy link

@Gehlot
Copy link

Gehlot commented May 9, 2016

How can i use this ? are there any project for this ?
Please give any one example.

@Gehlot
Copy link

Gehlot commented May 9, 2016

I have created one project and creating multiple subdomain based on our requirement.

@ravenet
Copy link

ravenet commented Oct 18, 2017

Hi,
I am trying to create sub directory base on ip address,
For example, my current website is www.nextan.biz, as my company expending business to following countryies, Australia, Singapore and Japan. So, i want to create url likes

www.nextan.biz/au/
www.nextan.biz/sg/
www.nextan.biz/jp/

I tried, to modify

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "welcome", action = "Index", id = UrlParameter.Optional}
);

routes.MapRoute(
name: "LocalizedDefault",
url: "{countrycode}/{controller}/{action}/{id}",
defaults: new { controller = "welcome", action = "Index", id = UrlParameter.Optional },
constraints: new { countrycode = "sg" }
);

countrycode - will change base on the client IP Address, but it is not working for me.

can you please help me to share some ideas.

Thank you

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