我找到了一个非常强大的方法。所以检查一下:)
首先,对于 Visual Studio 的应用程序开发服务器,您必须编辑“主机”文件。
以管理员身份打开记事本。为您的域添加任何名称,例如
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" }
);
将此路由放在默认路由之前。就是这样。
在约束中,您可以执行任何操作,例如检查子域名是否为客户商店名称或其他任何内容。