How to get the request URL on application startup
Sadly you are unable to retrieve the hosting URL of your application since that bit is controlled by IIS/WebListener etc. and doesn't flow through to the application directly.
Now a nice alternative is to provide each of your servers with an ASPNET_ENV
environment variable to then separate your logic. Here's some examples on how to use it:
Startup.cs:
public class Startup
{
public void Configure(IApplicationBuilder app)
{
// Will only get called if there's no method that is named Configure{ASPNET_ENV}.
}
public void ConfigureDev(IApplicationBuilder app)
{
// Will get called when ASPNET_ENV=Dev
}
}
Here's another example when ASPNET_ENV=Dev and we want to do class separation instead of method separation:
Startup.cs:
public class Startup
{
public void Configure(IApplicationBuilder app)
{
// Wont get called.
}
public void ConfigureDev(IApplicationBuilder app)
{
// Wont get called
}
}
StartupDev.cs
public class StartupDev // Note the "Dev" suffix
{
public void Configure(IApplicationBuilder app)
{
// Would only get called if ConfigureDev didn't exist.
}
public void ConfigureDev(IApplicationBuilder app)
{
// Will get called.
}
}
Hope this helps.
This won't give you the domain but may help if you're just running on a port and need access to that:
var url = app.ServerFeatures.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>().Addresses.Single();
Not sure what happens if you have multiple addresses bound.