How to use a SubDomain as Route Value in MVC2
first:
I did read and tried to implemented this and this and that, but I failed completely :(
my route is like:
routes.MapRoute开发者_如何学Go(
"DefaultRoute",
"{calurl}/{controller}/{action}/{id}",
new { calurl = "none", controller = "Subscriber", action = "Index", id = UrlParameter.Optional }
);
and I'm trying to use as
"{calurl}.domain.com",
"{controller}/{action}/{id}"
so the routed value calurl
would always come from the subdomain.
and I could have links like:
http://demo.domain.com/Subscriber/Register
as of today I have
http://domain.com/demo/Subscriber/Register
What I have tried
I tried to create my own CustomRoute
using the example of the links above (all 3, one at a time), and I end up always screwing everything.
and I'm keep thinking that it's to much code just to change RouteValue["calurl"]
to the subdomain.
What/How can I do this?
I am not sure if Routing extends to the actual domain name, as the domain or sub-domain should'nt have any effect on the working of a site/application.
I would suggest building your own sub-domain detection on each request. This keeps Routing and the Sub-domain detection separate and will help with testing etc..
This may 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();
}
If you have IIS7, why not use a URL Rewrite rule?
This would probably be better than doing a hack job with your routes, and IIS would do what it does best.
Probably something like this:
<rule name="rewriteSubdomains" stopProcessing="true">
<match url="(.*).domain.com/(.*)" />
<action type="Rewrite" url="domain.com/{R:1}/{R:2}" />
</rule>
This way, your route will handle the subdomain correctly, as it comes into the app differently.
精彩评论