我可以在这里使用路线约束吗?

RPM*_*984 4 asp.net-mvc domain-name asp.net-mvc-routing route-constraint asp.net-mvc-3

如果我有以下网址:

/ someurl

我有两个域名:

us.foo.com

au.foo.com

我希望这个200(匹配):

us.foo.com/someurl

但这到404(不匹配):

au.foo.com/someurl

路线看起来像这样:

RouteTable.Routes.MapRoute(
   "xyz route",
   "someurl",
   new { controller = "X", action = "Y" }
);
Run Code Online (Sandbox Code Playgroud)

我猜是因为没有路由值,我不能基于主机限制URL?那是对的吗?

如果是这样,我怎么能这样做,除了动作中的以下(丑陋):

if (cantViewThisUrlInThisDomain)
   return new HttpNotFoundResult();
Run Code Online (Sandbox Code Playgroud)

有人有任何想法吗?

我想我有点想通过它的域来限制路由,而不是路由令牌,如果这是有道理的.

Dar*_*rov 7

你可以写一个自定义路线:

    public class MyRoute : Route
    {
        public MyRoute(string url, object defaults)
            : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
        { }

        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            var url = httpContext.Request.Url;
            if (!IsAllowedUrl(url))
            {
                return null;
            }
            return base.GetRouteData(httpContext);
        }

        private bool IsAllowedUrl(Uri url)
        {   
            // TODO: parse the url and decide whether you should allow
            // it or not             
            throw new NotImplementedException();
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后在以下RegisterRoutes方法中注册它Global.asax:

routes.Add(
    "xyz route",
    new MyRoute(
        "{someurl}",
        new { controller = "Home", action = "Index" }
    )
);
Run Code Online (Sandbox Code Playgroud)