How can I route subdomain-based URLs in ASP.NET MVC5 using attribute-based routing ? I know this post , but we are trying to switch 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 routing subdomains, this standard code works:
[RoutePrefix("Account")]
public class AccountController : ApiController
{
[Route("Logout")]
public IHttpActionResult Logout()
{
}
}
To add subdomain-based routing, I wrote my own attribute and user restriction. The attributes are mostly replaced Route, so I can specify a subdomain, but my custom attribute is SubdomainRoutenot working. My attempt below. I assume that a more efficient implementation will also set up an attribute RoutePrefixto define 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?
source
share