Use settings from config files for `UseUrl(...)`?

asked9 years ago
last updated9 years ago
viewed10.1k times
Up Vote19Down Vote

I have an Asp.net core application with the following code.

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?

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();
}