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();
1
  • 1
    This might be helpful. Ultimately, you have to create your own instance of IConfiguration. Commented Feb 16, 2018 at 16:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I have a hard time to have access to environment name to add appSettings.{environment}.json file, how can I have access to it ?
Try this for inspiration. i.e. Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
An alternative would be to do it the same way WebHostBuilder does it, but that involves creating yet another IConfiguration first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.