MVC 3子域路由

时间:2011-03-25 17:56:56

标签: asp.net-mvc-3 routing subdomain

  

可能重复:
  Is it possible to make an ASP.NET MVC route based on a subdomain?

在asp.net MVC 3网站中,我想为用户创建在线商店。 用户创建的任何商店都应包含商店名称 .mydomain.com”等网址。

我尝试了一些路由工作但完全失败了。我正在研究解决方案但找不到合适的解决方案。

我的目的是;如果我可以添加路由来管理任何尝试查找子域的请求,我将检查它是否是用户在线商店名称并获取动态数据。

需要路由帮助:)谢谢。

2 个答案:

答案 0 :(得分:17)

我发现了一种非常强大的方式。所以检查一下:)

首先,对于visual studio的应用程序开发服务器,您必须编辑'hosts'文件。

以管理员身份打开记事本。为您的域添加任何名称,如

127.0.0.1 mydomain.com 127.0.0.1 sub1.mydomain.com

以及您在开发时需要使用的内容。

为您的Web项目提供特定的端口号。例如“45499”。通过这种方式,您可以通过在浏览器中写入来发送对项目的请求:

mydomain.com:45499 要么 sub1.mydomain.com:45499

那是准备步骤。让我们回答。

通过使用IRouteConstraint课程,您可以创建路线约束。

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;
    }
}

并在您想要使用的任何路线中添加约束。

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" }
                    ); 

将此路线放在默认路线之前。就是这样。

在约束中,您可以执行任何操作,例如检查子域名是客户端商店名称还是其他任何内容。

答案 1 :(得分:2)

您需要为*.mydomain.com添加一个dns条目以指向根应用程序,然后在根应用程序中处理请求时,检查请求主机以确定指定了哪个shopname