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

In ASP.NET Core 3.x Endpoints routing, how to specify domain name?

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

比如当请求URL为www.domain1.com/requestpathsub.domain1.com/requestpath时,我希望路由使用Domain1Routing.

但是如果请求URL是www.domain2.com/requestpathsub.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" }
      );
    });

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