Reputation: 221
I've a site hosted on the server and it has a sub domain. In my Global.asax.cs I've the map route as below
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "ShoppingCart", action = "Index",
id = UrlParameter.Optional }
);
and when I access the site subdomain like mysite.mydomain.com , i want it to be redicted to a sub domain something like
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "mySiteController", action = "Index",
id = UrlParameter.Optional }
);
but I'm not able to achieve this. How do I conditionally route based on the url accessed, from the Global.asax.cs
Thanks in advance.
Tarak
Upvotes: 1
Views: 1529
Reputation: 860
You could also create a custom route constraint for this scenario:
public class DomainRouteConstraint : IRouteConstraint {
string _host;
public DomainRouteConstraint(string host) {
_host = host;
}
public bool Match(HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection) {
return _host.Equals(httpContext.Request.Url.Host,
StringComparison.InvariantCultureIgnoreCase);
}
}
Then use the constraint in your route:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "mySiteController",
action = "Index",
id = UrlParameter.Optional}, // defaults
new DomainRouteConstraint("mysite.mydomain.com")); // constraint
or (to use multiple constraints in one route):
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "mySiteController",
action = "Index",
id = UrlParameter.Optional}, // defaults
new { ignored = DomainRouteConstraint("mysite.mydomain.com"),
/* add more constraints here ... */ }); // constraints
Upvotes: 1
Reputation: 28652
try this
routes.Add("DomainRoute", new DomainRoute(
"{Controller}.example.com", // Domain with parameters
"{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
))
For more information check out ASP.NET MVC Domain Routing link
Upvotes: 2