Reputation: 1171
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();
Upvotes: 1
Views: 3265
Reputation: 93053
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.
Upvotes: 2