我正在使用MVC。 我想在IIS上使用本地主机测试子域。 我创建子域所做的操作如下:
I added a line to windows host file
127.0.0.1 localhost 127.0.0.1 abc.localhost ::1 localhostI edited
applicationhost.configas:
<bindings>
<binding protocol="http" bindingInformation="*:59322:localhost" />
<binding protocol="http" bindingInformation="*:59322:abc.localhost" />
</bindings>
I added following class to
RouteConfig.cs:public class SubdomainRoute : RouteBase { public override RouteData GetRouteData(HttpContextBase httpContext) { var host = httpContext.Request.Url.Host; var index = host.IndexOf("."); string[] segments = httpContext.Request.Url.PathAndQuery.Split('/'); if (index < 0) return null; var subdomain = host.Substring(0, index); string controller = (segments.Length > 0) ? segments[0] : "Home"; string action = (segments.Length > 1) ? segments[1] : "Index"; var routeData = new RouteData(this, new MvcRouteHandler()); routeData.Values.Add("controller", controller); routeData.Values.Add("action", action); routeData.Values.Add("subdomain", subdomain); return routeData; } public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { //Implement your formating Url formating here return null; } }Now To get subdomain name in controller:
public string subdomainName { get { string s = Request.Url.Host; var index = s.IndexOf("."); if (index < 0) { return null; } var sub = s.Split('.')[0]; if (sub == "www" || sub == "localhsot") { return null; } return sub; } }My Index method is:
public string Index() { if (subdomainName == null) { return "No subdomain"; } return subdomainName; }
现在,URL http://localhost:59322/ 正常工作。但是URL http://abc.localhost:59322/ 出现错误:
错误请求 - 无效的主机名
HTTP错误400。请求的主机名无效。
我错在哪里了?为什么子域名不能正常工作?