【问题标题】:Subdomain on localhost gives Bad Request - Invalid Hostname error本地主机上的子域给出了错误的请求 - 无效的主机名错误
【发布时间】:2016-03-26 11:41:23
【问题描述】:

我正在使用 MVC。我想用 IIS 测试 localhost 上的子域。我为创建子域所做的是:

  1. 我在 windows 主机文件中添加了一行

    127.0.0.1       localhost
    127.0.0.1       abc.localhost
    ::1             localhost
    
  2. 我将applicationhost.config编辑为:

     <bindings>
           <binding protocol="http" bindingInformation="*:59322:localhost" />
           <binding protocol="http" bindingInformation="*:59322:abc.localhost" />
     </bindings>
  1. 我在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. 现在在控制器中获取子域名:

    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. 我的索引方法是:

    public string Index() { if (subdomainName == null) { return "No subdomain"; } return subdomainName; }

现在 url http://localhost:59322/ 工作正常。但是 url http://abc.localhost:59322/ 给出了错误

错误的请求 - 无效的主机名

HTTP 错误 400。请求主机名无效。

我做错了什么。为什么子域不起作用?

【问题讨论】:

  • 如果我的问题不清楚,请告诉我。
  • 3年前我问过这个问题,今天又遇到同样的问题,我也尝试以管理员身份运行vs,有人吗?

标签: c# asp.net asp.net-mvc subdomain asp.net-mvc-routing


【解决方案1】:

我知道已经很晚了,但供其他人参考,只需添加applicationhost.config

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

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 2016-10-20
    • 2015-08-17
    • 1970-01-01
    • 2020-12-23
    • 2019-11-30
    • 2016-04-15
    • 1970-01-01
    • 2016-08-24
    相关资源
    最近更新 更多