P
P
Pavel2012-02-02 21:19:29
ASP.NET
Pavel, 2012-02-02 21:19:29

How to create 3rd level virtual domains in ASP.NET MVC 3?

I want that when registering in the system, each user has his own page on the 3rd level domain of the pupkin.mysite.ru type.
How can I do this in ASP.NET MVC 3?
Let this be a virtual domain, which will then be interpreted by the system as mysite.ru/user/pupkin

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
DevMan, 2012-02-02
@region23

Maybe this will help.

X
x2bool, 2012-02-03
@x2bool

I did this: I added one parameter (domain) to routes.

routes.MapRoute(
    "Default",
    "${domain}/{controller}/{action}/{id}",
     new { domain = "", controller = "Home", action = "Index", id = "" }
);

Substitute $ for any symbol that you will not use in the url. Thus, we achieve the uniqueness of the domain identifier. Then, using the URL Rewrite Module for IIS 7, we set the rewrite rules so that requests for subdomains are redirected to the main domain, in accordance with the above route (add $ before the route ). I did it through the GUI in the IIS admin panel, so I can't provide the code.

V
Vladimir Dementiev, 2015-10-23
@SayMAN83

You have to write your own routing handler.
I used this option. I found the original version on one of the forums and modified it a bit.

public class SubDomainRoute : Route
    {
        private Regex domainRegex;
        private Regex pathRegex;
        private readonly string[] namespaces;
        public string Domain { get; set; }

        public SubDomainRoute(string domain, string url, object defaults, string[] namespaces)
            : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
        {
            Domain = domain;
            this.namespaces = namespaces;
        }

        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            // Build regex
            domainRegex = CreateRegex(Domain);
            pathRegex = CreateRegex(Url);

            // Request information
            string requestDomain = httpContext.Request.Headers["host"];
            if (!string.IsNullOrEmpty(requestDomain))
            {
                if (requestDomain.IndexOf(":") > 0)
                {
                    requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":"));
                }
            }
            else
            {
                requestDomain = httpContext.Request.Url.Host;
            }
            string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo;

            // Match domain and route
            Match domainMatch = domainRegex.Match(requestDomain);
            Match pathMatch = pathRegex.Match(requestPath);

            if (domainMatch.Success && pathMatch.Success)
            {
                var routeData = base.GetRouteData(httpContext);

                if (this.namespaces != null && this.namespaces.Length > 0)
                {
                    routeData.DataTokens["Namespaces"] = this.namespaces;
                }
                //тут добавляем поле {host} к маршрутам
                routeData.DataTokens["Host"] = routeData.Values["host"];
                routeData.DataTokens["UseNamespaceFallback"] = bool.FalseString;

                return routeData;
            }

            return null;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
           
                return base.GetVirtualPath(requestContext, values);
           // return null;
        }

        private Regex CreateRegex(string source)
        {
            // Perform replacements
            source = source.Replace("/", @"\/?");
            source = source.Replace(".", @"\.?");
            source = source.Replace("-", @"\-?");
            source = source.Replace("{", @"(?<");
            source = source.Replace("}", @">([a-zA-Z0-9_]*))");

            return new Regex("^" + source + "$");
        }
    }

And then I describe the route like this:
routes.Add("host_default", new SubDomainRoute(
                "{host}.web.ru",
                "{controller}/{action}/{id}",
                new { controller = "User", action = "Index", id = UrlParameter.Optional },
                new[] { typeof(Controllers.UserController).Namespace } // Namespaces defaults
            ));

It is also necessary to check the correctness of the subdomain in the User controller.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question