MVC 3 Subdomain Routing [duplicate]

好久不见. 提交于 2019-11-27 17:24:27
Bahtiyar Özdere

I have found a very powerful way. So check this :)

First of all for application development server of visual studio you have to edit the 'hosts' file.

Open notepad as administrator. Add any name for your domain something like

127.0.0.1 mydomain.com 127.0.0.1 sub1.mydomain.com

and what you need to use on development.

After give a specific port number to your web project. For example "45499". By this way you will be able to sen request to your project by writing in browser :

mydomain.com:45499 or sub1.mydomain.com:45499

That was the preparing step. Lets get on the answer.

By using the IRouteConstraint class you can create your route constrains.

public class SubdomainRouteConstraint : IRouteConstraint
{
    private readonly string SubdomainWithDot;

    public SubdomainRouteConstraint(string subdomainWithDot)
    {
        SubdomainWithDot = subdomainWithDot;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var url = httpContext.Request.Headers["HOST"];
        var index = url.IndexOf(".");

        if (index < 0)
        {
            return false;
        }
        //This will bi not enough in real web. Because the domain names will end with ".com",".net"
        //so probably there will be a "." in url.So check if the sub is not "yourdomainname" or "www" at runtime.
        var sub = url.Split('.')[0];
        if(sub == "www" || sub == "yourdomainname" || sub == "mail")
        {
            return false;
        }

        //Add a custom parameter named "user". Anything you like :)
        values.Add("user", );
        return true;
    }
}

And add your constrain in any route you would like to use.

routes.MapRoute(
                    "Sub", // Route name
                    "{controller}/{action}/{id}", // URL with parameters
                    new { controller = "SubdomainController", action = "AnyActionYouLike", id = UrlParameter.Optional },
                    new { controller = new SubdomainRouteConstraint("abc.") },
                    new[] { "MyProjectNameSpace.Controllers" }
                    ); 

Put this routes before your default route. That's all.

In the constraint you may do anything like check for subdomain name is a client shop name or whatever.

You'll need to add a dns entry for *.mydomain.com to point at the root application, then when handling the request in the root application, check the request host to determine which shopname is specified.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!