I want to be able to route to a different controller based on the domain name of the URL.
For example, when the request URL is www.domain1.com/requestpath
or sub.domain1.com/requestpath
, I want the routing to use Domain1Routing
.
But if the request URL is www.domain2.com/requestpath
or sub.domain2.com/requestpath
, I want the routing to be handled by Domain2Routing
.
The following code doesn't work. Do I need to specify the pattern differently? Or use different method than 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" }
);
});
As @JeremyCaney mentioned, what worked is using the RequireHost() extension method:
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");
);
});