1

On an asp.net core 2 web api, I want to be able to set the url on which my api will listen (api run as windows service) based on a value in appsettings.json file. I can't find a way to achive it, how can I have acces to an instance of IConfiguration ?

var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);

return WebHost.CreateDefaultBuilder(args)
    .UseContentRoot(pathToContentRoot)
    .UseStartup<Startup>()
    .UseUrls({value_from_appsettings})
    .Build()
    .RunAsService();
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Nicolas Boisvert
  • 1,141
  • 2
  • 10
  • 26
  • 1
    [This](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/hosting?tabs=aspnetcore2x#overriding-configuration) might be helpful. Ultimately, you have to create your own instance of `IConfiguration`. – Kirk Larkin Feb 16 '18 at 16:47

1 Answers1

2

In order to gain access to the configuration before you go down the WebHost.CreateDefaultBuilder path, you'll need to build your own IConfiguration instance using ConfigurationBuilder.

Taking the example from your question, you can use something like the following:

var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);

var appSettingsConfiguration = new ConfigurationBuilder()
    .SetBasePath(pathToContentRoot)
    .AddJsonFile("appsettings.json")
    .Build();

return WebHost.CreateDefaultBuilder(args)
    .UseContentRoot(pathToContentRoot)
    .UseStartup<Startup>()
    .UseUrls(appSettingsConfiguration["Your:Value"])
    .Build()
    .RunAsService();

This is somewhat explained in the docs where the example uses instead a hosting.json file to set this up. It also makes use of UseConfiguration, which allows you to specify a value for e.g. urls, which will be picked up automatically.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
  • I have a hard time to have access to environment name to add appSettings.{environment}.json file, how can I have access to it ? – Nicolas Boisvert Feb 19 '18 at 13:31
  • Try [this](https://stackoverflow.com/questions/44437325/access-environment-name-in-program-main-in-asp-net-core) for inspiration. i.e. `Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")` – Kirk Larkin Feb 19 '18 at 13:46
  • An alternative would be to do it the same way `WebHostBuilder` [does it](https://github.com/aspnet/Hosting/blob/release/2.0/src/Microsoft.AspNetCore.Hosting/WebHostBuilder.cs#L44), but that involves creating yet *another* `IConfiguration` first. – Kirk Larkin Feb 19 '18 at 13:57