如何使用基于属性的路由在ASP.NET MVC5 中执行基于子域的URL路由?我知道this post但我们正在尝试采用更清晰的基于属性的方法,我想移动我的路线
来自http://domain.com/Account/Logout/
到http://my.domain.com/Account/Logout/
没有子域路由,此标准代码可以工作:
[RoutePrefix("Account")]
public class AccountController : ApiController
{
[Route("Logout")]
public IHttpActionResult Logout()
{
// logic
}
}
要添加基于子域的路由,我编写了自定义属性和自定义约束。基本上替换了Route
属性,因此我可以指定子域,但我的自定义SubdomainRoute
属性不起作用。我的尝试如下。我假设更好的实现还会自定义RoutePrefix
属性以指定子域...
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;
}
}
}
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);
}
}
关于如何使这项工作的任何想法?