aspnet / MetaPackages

[Archived] NuGet meta packages. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
211 stars 109 forks source link

CreateDefaultBuilder() does not load and apply appsettings.json #247

Closed 686d7066 closed 6 years ago

686d7066 commented 6 years ago

Hello,

we have a dotnet core 2.0 application with an "appsettings.json" in the root of the project. When starting the application using the code desribed in the "Migrating from ASP.NET Core 1.x to ASP.NET Core 2.0" blog post the settings are not loaded as expected. This is especially visible as the set Url is not used to start the application.

The appsettings.json in question:

{
    "ConnectionStrings, Logging, etc.":  ...
    "Urls": "http://localhost:5005/",
    "Environment": "Development"
}

The code in use:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)    
        .UseStartup<Startup>()
        .Build();
}

For testing we switch back to ye olde way and it works :

public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true)
            .Build();

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseConfiguration(configuration)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

        host.Run();
    }
}

Now the application starts under the expected Url. It also works if we set the App URL in the properties but we´d prefer to be able to configure everything in one file.

According to the blog post, the CreateDefaultBuilder should load the appsettings.json automatically and apply the configuration. We´ve looked up the code here on GitHub and it seems as if it should work as expected so maybe we are missing something (obvious) here?

Tratcher commented 6 years ago

The catch here is that Environment and Urls are host/server settings, loading them at the app settings stage (ConfigureAppConfiguration) is too late. Your last example loads them into the host configuration (UseConfiguration).

See https://github.com/aspnet/MetaPackages/blob/f0de53c661a3c01f5cd446a802231365a82f5026/src/Microsoft.AspNetCore/WebHost.cs#L153

686d7066 commented 6 years ago

Understood, thanks for the information!