I am using MVC. I want to test subdomains on localhost with IIS. What I have done to create a subdomain is:
I added a line to windows host file
127.0.0.1 localhost
127.0.0.1 abc.localhost
::1 localhost
I edited applicationhost.config
as:
<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;
}
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?
I know it is very late but for reference to others , just add in applicationhost.config
:
<bindings>
<binding protocol="http" bindingInformation="*:59322:" />
</bindings>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With