How to use SubDomain as a route value in MVC2

first:

I read and tried to implement this and this and which , but I failed completely: (

my route is like:

routes.MapRoute( "DefaultRoute", "{calurl}/{controller}/{action}/{id}", new { calurl = "none", controller = "Subscriber", action = "Index", id = UrlParameter.Optional } ); 

and I'm trying to use both

 "{calurl}.domain.com", "{controller}/{action}/{id}" 

therefore, the routed calurl value calurl always come from the subdomain.

and I could have links like:

 http://demo.domain.com/Subscriber/Register 

Today I have

 http://domain.com/demo/Subscriber/Register 

What i tried

I tried to create my own CustomRoute using the example links above (all 3, one at a time), and I end up screwing up all the time.

and I keep thinking that this is a lot of code to change RouteValue["calurl"] to a subdomain.

What / How can I do this?

+4
source share
2 answers

I am not sure that routing extends to the actual domain name, since the domain or subdomain should not affect the operation of the site / application.

I would suggest creating your own subdomain discovery for each request. This allows you to distinguish between routing and subdomain discovery and will help with testing, etc.

This can help:

 public static string GetSubDomain() { string subDomain = String.Empty; if (HttpContext.Current.Request.Url.HostNameType == UriHostNameType.Dns) { subDomain = Regex.Replace(HttpContext.Current.Request.Url.Host, "((.*)(\\..*){2})|(.*)", "$2").Trim().ToLower(); } if (subDomain == String.Empty) { subDomain = HttpContext.Current.Request.Headers["Host"].Split('.')[0]; } return subDomain.Trim().ToLower(); } 
+1
source

If you have IIS7, why not use the Rewrite URL rule?

This would probably be better than hacking your routes, and IIS will do what it does best.

Maybe something like this:

 <rule name="rewriteSubdomains" stopProcessing="true"> <match url="(.*).domain.com/(.*)" /> <action type="Rewrite" url="domain.com/{R:1}/{R:2}" /> </rule> 

Thus, your route will handle the subdomain correctly, since it enters the application in different ways.

+1
source

All Articles