How can one perform subdomain based URL routing in ASP.NET MVC5 using attribute based routing? I'm aware of this post but we're trying to move to a cleaner attribute based approach and I would like to move my route
from http://domain.com/Account/Logout/
to http://my.domain.com/Account/Logout/
Without subdomain routing, this standard code works:
[RoutePrefix("Account")]
public class AccountController : ApiController
{
[Route("Logout")]
public IHttpActionResult Logout()
{
// logic
}
}
To add subdomain based routing, I wrote a custom attribute and a custom constraint. Basically replaced the Route
attributes so I can specify the subdomain but my custom SubdomainRoute
attribute doesn't work. My attempt is below. I presume a better implementation would also customize the RoutePrefix
attribute to specify subdomains ...
SubdomainRoute
public class SubdomainRouteAttribute : RouteFactoryAttribute
{
public SubdomainRouteAttribute(string template, string subdomain) : base(template)
{
Subdomain = subdomain;
}
public string Subdomain
{
get;
private set;
}
public override RouteValueDictionary Constraints
{
get
{
var constraints = new RouteValueDictionary();
constraints.Add("subdomain", new SubdomainRouteConstraint(Subdomain));
return constraints;
}
}
}
SubdomainRouteConstraint
public class SubdomainRouteConstraint : IRouteConstraint
{
private readonly string _subdomain;
public SubdomainRouteConstraint(string subdomain)
{
_subdomain = subdomain;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return httpContext.Request.Url != null && httpContext.Request.Url.Host.StartsWith(_subdomain);
}
}
Any ideas on how to make this work?