简体   繁体   中英

Subdomain redirecting to root in MVC 3

I'm experiencing a frustratingly perplexing issue with regards to subdomains on an MVC 3 application. Using the code below, my subdomain routes me back to the root of my domain everytime.

When I enter subdomain.mydomain.com it routes me to domain.com?nr=0. I can't find why, or where in code, it's appending the querystring value.

 public class SubdomainRoute : RouteBase
    {
        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 (!String.IsNullOrEmpty(subDomain) && subDomain != "www" && subDomain != "mydomain")
            {
                var routeData = new RouteData(this, new MvcRouteHandler());
                routeData.Values.Add("controller", "External"); 
                routeData.Values.Add("action", "CoolAction"); 
                routeData.Values.Add("subdomain", subDomain);

                return routeData;
            }
            else
                return null;
        } 
}

I disabled my forms authentication, but that didn't fix it. I also have a url rewrite that prepends www. to all requests, if www. is missing - I also removed that and it didn't fix it. Below is the RegisterRoutes of my Global.asax:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("elmah.axd");

        routes.Add(null, new SubdomainRoute());

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new[] { "MyProject.UI.Web.Controllers" }
        );
        routes.MapRoute("NotesController",
                        "Notes/{noteDestinationType}/{noteDestinationGuid}",
                        new { controller = "Notes", action = "SaveNote" });
    }

I've been banging my head on this all day long and I give up. I'm asking for help. TIA.

I think you are missing regex.Split(url); See more

            var url = httpContext.Request.RawUrl;
            Regex regex = new Regex("/");
            string[] substrings = regex.Split(url);
            var index = host.IndexOf(".");
            var subDomain = host.Substring(0, index);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM