Mike-E
Mike-E

Reputation: 2475

How Do You Access the `applicationUrl` Property Found in launchSettings.json from Asp.NET Core 3.1 Startup class?

I am currently creating an Asp.NET Core 3.1 API Application. In it, I have a launchSettings.json that looks like the following:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:61392",
      "sslPort": 44308
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "Key": "Value",
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Application.API": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "https://localhost:5001;http://localhost:5000"
    }
  }
}

In particular, I am interested in obtaining the applicationUrl values defined in this file. Unfortunately, I do not see any obvious way to access them outside of loading the file directly via JSON serialization and probing the values there.

As such, I am looking for a more elegant solution. Is there a way to access these values from within the Startup.Configure and/or Startup.ConfigureServices methods?

I am thinking of something like:

public void Configure(IApplicationBuilder builder)
{
    var url = builder.ApplicationServices.GetRequiredService<IServerHostingEnvironment>().ApplicationUrl
}

For reference, I did see this question, but it seems that this requires an HTTP request. In my case, I am still configuring the server before a request has been made.

For further reference and context: I am building a .NET GitHub App application, and am making the corresponding equivalent of the Smee.io client, whose Javascript code can be found here.

The client takes a source (via Server-sent events) and sends it to a target. I got the source figured out and configured, but am ironically having trouble accessing and establishing the target URL (the applicationUrl seen above) in an obvious and configured fashion.

Finally, I realize I could hardcode the value in appSettings.json, but that would then mean I would be maintaining the same value in two places -- one in appSettings.json and one in the already-existing launchSettings.json. I would rather keep it to one place to reduce maintenance burden, if possible.

Upvotes: 19

Views: 28410

Answers (5)

Zonorai
Zonorai

Reputation: 129

Have not tested it but I use this pattern to access appsettings.json.

In startup.cs add launchsettings.json to the configuration builder:

public Startup(IConfiguration configuration)
{
    var builder = new ConfigurationBuilder().AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "Properties", "launchSettings.json"));
    Configuration = builder.Build();
}

public IConfiguration Configuration { get; }

Add it as a service:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton <IConfiguration> (Configuration);
}

    

Inject it in controller and get key value:

public class SomeController: ControllerBase 
{  
    private IConfiguration _iconfiguration;  
    public SomeController(IConfiguration iconfiguration) 
    {  
        _iconfiguration = iconfiguration;  
    }

    void SomeMethod()
    {
        string appUrl = _iConfiguration.GetValue<string>("applicationUrl","someDefaultValue")
    }
}

Upvotes: 4

ertugrulakdag
ertugrulakdag

Reputation: 95

            Url = new Uri($"{Environment.GetEnvironmentVariable("ASPNETCORE_URLS").Split(";").First()}/mini-profiler/results-index")

Upvotes: 0

Alex White
Alex White

Reputation: 187

I know, one year has passed, but this solution may be useful for somebody:

var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables()
                .Build();
var appUrl = configuration["ASPNETCORE_URLS"].Split(";").First();

Upvotes: 2

garlicbread
garlicbread

Reputation: 361

I was actually looking for something similar myself recently.

It turns out you can determine what URL's were passed to the application by Visual Studio during a debugging session (from applicationUrl within launchSettings.json) By looking at the environmental variables.

Although bearing in mind this is probably only useful for debugging within VStudio IDE which uses the launchSettings.json file

var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS").Split(";");

Upvotes: 12

aweyeahdawg
aweyeahdawg

Reputation: 1016

In your Startup constructor, you can get an IConfiguration from dependency injection. With this, you can access properties inside your appsettings.json by using the configuration like so:

var appUrl = _configuration["profiles:applicationUrl"];

If you will be accessing many properties inside your appsettings.json you can use the IConfiguration.Bind() method to bind all properties within your configuration json to a class instance. For instance, you would have:

public class Config
{
   public Profile Profiles { get; set; }
}
public class Profile
{
   public string ApplicationUrl { get; set; }
}

Then in ConfigureServices:

var config = new Config();
_configuration.Bind(config);

Then if you register config into the serviceprovider you can access your configuration anywhere through DI:

services.AddSingleton(config);

EDIT

To add json files other than the default appsettings.json, call ConfigureAppConfiguration() on the IWebHostBuilder after CreateDefaultBuilder in Program.cs documented below.

Link to File Configuration Docs

In the callback parameter you can add as many json,xml,ini files into the configuration you want, then use my answer above to get any values from all files. Note that if two of the same key is present, the last value for that key will be used.

Upvotes: 0

Related Questions