子域不适用于默认路由

时间:2015-07-14 13:31:45

标签: asp.net asp.net-mvc

我在RouteConfig.cs中创建了一个子域路由类:

public class SubdomainRoute : RouteBase
    {
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            if (httpContext.Request == null || httpContext.Request.Url == null)
            {
                return null;
            }
            var host = httpContext.Request.Url.Host;
            var index = host.IndexOf(".");
            string[] segments = httpContext.Request.Url.PathAndQuery.TrimStart('/').Split('/');
            if (index < 0)
            {
                return null;
            }
            var subdomain = host.Substring(0, index);
            string[] blacklist = { "www", "yourdomain", "mail","localhost" };
            if (blacklist.Contains(subdomain))
            {
                return null;
            }
            string controller = (segments.Length > 0) ? segments[0] : "Home";
            if (controller == "")
                controller = "Home";
            string action = (segments.Length > 1) ? segments[1] : "Index";
            var routeData = new RouteData(this, new MvcRouteHandler());
            routeData.Values.Add("controller", controller);
            routeData.Values.Add("action", action);
            routeData.Values.Add("subdomain", subdomain);
            return routeData;
        }
        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            return null;
        }
    }

我将RegisterRoutes功能更新为:

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

            routes.Add(new SubdomainRoute());

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{category}/{subcategory}/{lowcategory}/{id}",
                defaults: new { controller = "Home", action = "Index",category=UrlParameter.Optional,subcategory=UrlParameter.Optional,lowcategory=UrlParameter.Optional, id = UrlParameter.Optional }
            );
        }

我的索引功能是:

public string Index(string category, string subcategory, string lowcategory,int? id)

现在,链接http://localhost:29808/Home/Index/mobiles/Htc/M8/3工作正常但子网域无法正常工作electronics.localhost:29808/Home/Index/mobiles/HTC/M8/3。 (它在类别和子类别中显示为null)。如果必须包括什么才能使它工作?

0 个答案:

没有答案