实现此目的的一种方法是创建一个custom route constraint 来指定每个域名的路由功能。
域约束
public class DomainConstraint : IRouteConstraint
{
private readonly string[] domains;
public DomainConstraint(params string[] domains)
{
this.domains = domains ?? throw new ArgumentNullException(nameof(domains));
}
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
string domain =
#if DEBUG
// A domain specified as a query parameter takes precedence
// over the hostname (in debug compile only).
// This allows for testing without configuring IIS with a
// static IP or editing the local hosts file.
httpContext.Request.Query["domain"];
#else
null;
#endif
if (string.IsNullOrEmpty(domain))
domain = httpContext.Request.Host.Host;
return domains.Contains(domain);
}
}
用法
app.UseMvc(routes =>
{
routes.MapRoute(
name: "DomainA",
template: "route",
defaults: new { controller = "DomainA", action = "Route" },
constraints: new { _ = new DomainConstraint("domaina.com") });
routes.MapRoute(
name: "DomainB",
template: "route",
defaults: new { controller = "DomainB", action = "Route" },
constraints: new { _ = new DomainConstraint("domainb.com") });
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
请注意,如果您在 Visual Studio 中启动它,它将无法使用标准配置。为了在不更改配置的情况下轻松调试,您可以将带有域的 URL 指定为查询字符串参数:
/route?domain=domaina.com
这只是为了让您不必重新配置 IIS 和您的本地主机文件来进行调试(尽管如果您愿意,您仍然可以这样做)。在 Release 构建期间,此功能已被删除,因此它仅适用于生产中的实际域名。
由于路由默认响应所有域名,因此只有在域之间共享大量功能时才有意义。如果没有,最好为每个域设置单独的区域:
routes.MapRoute(
name: "DomainA",
template: "{controller=Home}/{action=Index}/{id?}",
defaults: new { area = "DomainA" },
constraints: new { _ = new DomainConstraint("domaina.com") }
);
routes.MapRoute(
name: "DomainA",
template: "{controller=Home}/{action=Index}/{id?}",
defaults: new { area = "DomainB" },
constraints: new { _ = new DomainConstraint("domainb.com") }
);