我在服务器上托管了一个站点,它有一个子域。在我的Global.asax.cs中我的地图路线如下
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "ShoppingCart", action = "Index",
id = UrlParameter.Optional }
);
当我访问像mysite.mydomain.com这样的网站子域名时,我希望它被重新定义为子域名,如
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "mySiteController", action = "Index",
id = UrlParameter.Optional }
);
但我无法实现这一目标。 如何根据从Global.asax.cs
访问的URL有条件地路由提前致谢。
塔拉克
答案 0 :(得分:2)
试试这个
routes.Add("DomainRoute", new DomainRoute(
"{Controller}.example.com", // Domain with parameters
"{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
))
有关详细信息,请查看ASP.NET MVC Domain Routing链接
答案 1 :(得分:1)
您还可以为此方案创建自定义路线约束:
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);
}
}
然后在路线中使用约束:
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
或(在一个路线中使用多个约束):
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