.NET MVC 中的路由问题

本文关键字:路由 问题 MVC NET | 更新日期: 2023-09-27 18:34:15

可能的重复项:
如何通过网址获取路由数据?

public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            var url = httpContext.Request.Headers["HOST"];
            var index = url.IndexOf(".");
            if (index < 0)
                return null;
            var subDomain = url.Substring(0, index);
            if (subDomain != "www" && subDomain != "m")
            {
                var routeData = new RouteData(this, new MvcRouteHandler());
                    routeData.Values.Add("controller", "Business"); 
                    routeData.Values.Add("action", "Display"); 
                    routeData.Values.Add("id", subDomain);
                return routeData;
            }
            if (subDomain == "m")
            {
                var routeData = new RouteData(this, new MvcRouteHandler());
                routeData.Values.Add("controller", "Mobile"); 
                routeData.Values.Add("action", "Index"); 
                return routeData;
            }
            return null;
        }

我的问题是,当我访问xyz.mydomain.com时,它总是被重新路由到xyz.mydomain.com/Business/Display/xyz。 这阻止我去xyz.mydomain.com/Overview因为它正在拾取子域并重定向。

我尝试使用 if 语句来确定是否指定了控制器,但似乎没有任何效果。 有什么建议吗?

.NET MVC 中的路由问题

以防万一其他人需要答案,这是我的解决方案......
substrings.Length >= 3是针对控制器的,然后是一个操作,因此如果您只需要一个控制器,请更改为 2:

public override RouteData GetRouteData(HttpContextBase httpContext)
            {
                var host = httpContext.Request.Headers["HOST"];
                var url = httpContext.Request.RawUrl;
                Regex regex = new Regex("/");
                string[] substrings = regex.Split(url);
                if (substrings.Length >= 3)
                {
                    return null;
                }
                var index = host.IndexOf(".");
                if (index < 0)
                {
                    return null;
                }
                var subDomain = host.Substring(0, index);
                if (subDomain != "www" && subDomain != "m")
                {
                    var routeData = new RouteData(this, new MvcRouteHandler());
                        routeData.Values.Add("controller", "Business"); //Goes to the User1Controller class
                        routeData.Values.Add("action", "Display"); //Goes to the Index action on the User1Controller
                        routeData.Values.Add("id", subDomain);
                    return routeData;
                }
                if (subDomain == "m")
                {
                    var routeData = new RouteData(this, new MvcRouteHandler());
                    routeData.Values.Add("controller", "Mobile"); //Goes to the User2Controller class
                    routeData.Values.Add("action", "Index"); //Goes to the Index action on the User2Controller
                    return routeData;
                }
                return null;
            }