基于MVC5属性的子域路由?

时间:2014-04-04 00:30:14

标签: asp.net asp.net-mvc attributes asp.net-mvc-routing

如何使用基于属性的路由在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属性以指定子域...

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

关于如何使这项工作的任何想法?

0 个答案:

没有答案