本地主机上的子域名出现“Bad Request - Invalid Hostname”错误

6

我正在使用MVC。 我想在IIS上使用本地主机测试子域。 我创建子域所做的操作如下:

  1. I added a line to windows host file

    127.0.0.1       localhost
    127.0.0.1       abc.localhost
    ::1             localhost
    
  2. I edited applicationhost.config as:

     <bindings>
           <binding protocol="http" bindingInformation="*:59322:localhost" />
           <binding protocol="http" bindingInformation="*:59322:abc.localhost" />
     </bindings>
  1. 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; } }

  2. 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;
                }
            }
    
  3. 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。请求的主机名无效。

我错在哪里了?为什么子域名不能正常工作?


1
请告诉我如果我的问题不清楚。 - Irfan Y
我3年前问过这个问题,今天又遇到了同样的问题,我也尝试以管理员身份运行VS,有人知道怎么解决吗? - Irfan Y
1个回答

7

虽然有些晚了,但是为了其他人参考,只需在 applicationhost.config 中添加:

<bindings>
     <binding protocol="http" bindingInformation="*:59322:" />
</bindings>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,