How to get the request URL at application startup

I am trying to find the request URL (domain specifically) when starting the application in my Startup.cs file.

public Startup(IHostingEnvironment env) { Configuration = new Configuration().AddEnvironmentVariables(); string url = ""; } 

I need this in the Startup.cs file because it will determine which temporary services will be added later in the startup class, in the ConfigureServices method.

What is the correct way to get this information?

+6
source share
2 answers

Unfortunately, you cannot get the host URL of your application, since this bit is controlled by IIS / WebListener, etc. and does not apply directly to the application.

Now, a good alternative is to provide each of your servers with the ASPNET_ENV environment variable ASPNET_ENV that you can separate your logic. Here are some examples of how to use it:

Startup.cs:

 public class Startup { public void Configure(IApplicationBuilder app) { // Will only get called if there no method that is named Configure{ASPNET_ENV}. } public void ConfigureDev(IApplicationBuilder app) { // Will get called when ASPNET_ENV=Dev } } 

Here is 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.

+4
source

This will not give you a domain, but it can help if you just work on a port and need access to it:

  var url = app.ServerFeatures.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>().Addresses.Single(); 

Not sure what will happen if you have multiple addresses.

+1
source

Source: https://habr.com/ru/post/981731/


All Articles