Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
}
like image 236
ca9163d9 Avatar asked Sep 19 '16 18:09

ca9163d9


1 Answers

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.

like image 111
ChaoticCoder Avatar answered Oct 05 '22 07:10

ChaoticCoder