Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subdomain on localhost gives Bad Request - Invalid Hostname error

I am using MVC. I want to test subdomains on localhost with IIS. What I have done to create a subdomain is:

  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; }

Now the url http://localhost:59322/ is working fine. But the url http://abc.localhost:59322/ gives the error

Bad Request - Invalid Hostname

HTTP Error 400. The request hostname is invalid.

What I am doing wrong. Why the subdomain is not working?

like image 689
Irfan Yusanif Avatar asked Dec 20 '15 04:12

Irfan Yusanif


1 Answers

I know it is very late but for reference to others , just add in applicationhost.config :

<bindings>
     <binding protocol="http" bindingInformation="*:59322:" />
</bindings>
like image 109
tchno0l0ogy Avatar answered Nov 14 '22 23:11

tchno0l0ogy