user2095880
user2095880

Reputation:

How to get the request URL on application startup

I'm trying to find the request URL (the domain specifically) when the application starts, in my Startup.cs file..

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

I need it in the Startup.cs file because it will determine what transient services are added later in the startup class, in the ConfigureServices method.

What is the correct way of getting this information?

Upvotes: 9

Views: 9788

Answers (2)

Simon_Weaver
Simon_Weaver

Reputation: 146020

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.

Upvotes: 3

N. Taylor Mullen
N. Taylor Mullen

Reputation: 18301

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.

Upvotes: 4

Related Questions