MVC 3子域路由

Bah*_*ere 28 subdomain routing asp.net-mvc-3

可能重复:
是否可以基于子域创建ASP.NET MVC路由?

在asp.net MVC 3网站中,我想为用户创建在线商店.用户创建的任何商店都应该具有" shopname .mydomain.com"之类的URL .

我尝试了一些路由工作,但都失败了.我正在研究解决方案,但找不到任何合适的解决方案.

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

需要路由帮助:)谢谢.

Bah*_*ere 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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" }
                    ); 
Run Code Online (Sandbox Code Playgroud)

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

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

  • 哇,就在我虽然MVC足够凉爽的时候,它还可以梳理头发并吸一支烟. (9认同)
  • 在构造函数中分配SubdomainWithDot的目的是什么? (3认同)

Nic*_*sen 2

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