在 ASP.NET Core 3.x Endpoints 路由中,如何指定域名?

Posted

技术标签:

【中文标题】在 ASP.NET Core 3.x Endpoints 路由中,如何指定域名?【英文标题】:In ASP.NET Core 3.x Endpoints routing, how to specify domain name? 【发布时间】:2020-08-07 05:22:20 【问题描述】:

我希望能够根据 URL 的域名路由到不同的控制器。

比如当请求的URL是www.domain1.com/requestpath或者sub.domain1.com/requestpath,我希望路由使用Domain1Routing

但是如果请求的URL是www.domain2.com/requestpath或者sub.domain2.com/requestpath,我希望路由由Domain2Routing处理。

以下代码不起作用。我需要以不同的方式指定 pattern 吗?还是使用与MapControllerRoute()不同的方法?

app.UseRouting();

app.UseEndpoints(
    endpoints => 
      endpoints.MapControllerRoute(
          name: "Domain1Routing",
          pattern: "subdomain.domain1.com/requestpath",
          defaults: new  controller = "Domain1", action = "Index" 
      );
      endpoints.MapControllerRoute(
          name: "Domain2Routing",
          pattern: "subdomain.domain2.com/requestpath",
          defaults: new  controller = "Domain2", action = "Index" 
      );
    );

【问题讨论】:

这并不能解决您的问题,因为您希望根据主机名条件概括这些路由,但值得注意的是,您至少可以 restrict 路由到使用RequireHost() 扩展方法来指定特定的主机名。 @JeremyCaney 谢谢。我刚刚发现了同样的事情。将为适合我的解决方案写一个答案。 【参考方案1】:

正如@JeremyCaney 提到的,有效的是使用 RequireHost() 扩展方法:

app.UseRouting();

app.UseEndpoints(
    endpoints => 
      endpoints.MapControllerRoute(
          name: "Domain1Routing",
          pattern: "*requestpath",
          defaults: new  controller = "Domain1", action = "Index" .RequireHost("*.domain1.com");
      );
      endpoints.MapControllerRoute(
          name: "Domain2Routing",
          pattern: "*requestpath",
          defaults: new  controller = "Domain2", action = "Index" .RequireHost("*.domain2.com");
      );
    );

【讨论】:

我很高兴你能解决这个问题。另一种选择——如果你在主机名:控制器之间有 1:1 映射可能会更优雅——将使用 new(er)[Host] attribute。我在my answer to a similar question 上提供了这两种方法的示例。 @JeremyCaney HostAttribute 的问题是,AFAIK,您必须对您的域名进行硬编码 - 我更希望能够从配置中加载它们。

以上是关于在 ASP.NET Core 3.x Endpoints 路由中,如何指定域名?的主要内容,如果未能解决你的问题,请参考以下文章