I have an Asp.net core application with the following code.
Program.cs
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls("http://*:5000")
......
I don't want to hard code the port number 5000. How to read it from the configure file?
The startup.cs uses the config file for some settings. Should the code be duplicated in the program.cs? But how to get IHostingEnvironment env
?
Startup.cs
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
Reading config value as mentioned by @Set above but using it in CreateHostBuilder()
works for WebHost.
private static string GetHostPort()
{
var config = new ConfigurationBuilder()
.AddJsonFile(SelfHostSettings, optional: false, reloadOnChange: false)
.Build();
return config["HostPort"] ?? "8080";
}
private static IHostBuilder CreateHostBuilder(string[] args)
{
var hostPort = GetHostPort();
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(GetConfig)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls($"http://localhost:{hostPort}");
webBuilder.UseStartup<Startup>();
})
.UseWindowsService();
}
Note that trying to read config from Main()
defaults the directory to %windir%\system32
but calling the same from CreateHostBuilder()
is set to application directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With