【问题标题】:Can i use a route constraint here?我可以在这里使用路线约束吗?
【发布时间】:2011-08-29 06:11:45
【问题描述】:

如果我有以下网址:

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

我猜是因为没有路由值,我不能根据主机限制 URL?对吗?

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

if (cantViewThisUrlInThisDomain)
   return new HttpNotFoundResult();

有人有什么想法吗?

我想我正在寻找一种通过其域而不是路由令牌来约束路由的方法,如果这有意义的话。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-routing domain-name route-constraint


    【解决方案1】:

    您可以编写自定义路线:

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

    然后在Global.asaxRegisterRoutes方法中注册:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2011-01-25
      • 1970-01-01
      • 2017-11-02
      相关资源
      最近更新 更多