ASP.NET CoreConfiguration configuration priority details

Posted by truck7758 on Tue, 08 Mar 2022 09:42:07 +0100

ASP.NET Core project starts. The default execution sequence is: Host - > read configuration - > log settings - > registration service (DI) - > Add Middleware - > webhost listening - > background Work start.

The loading and reading of configuration is at the beginning of the startup process. Microsoft about ASP Configuration documents in net core: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0

Host. In the createdefaultbuilder method, the default configuration is provided for the application in the following order:

  • ChainedConfigurationProvider: add an existing as the source. In the default configuration example, add the host configuration and set it as the first source to apply the configuration.
  • Use Appsettings appsettings.json json.
  • Use the JSON configuration provider through Appsettings JSON. For example, Appsettings Production. JSON and Appsettings Development. json.
  • The application secret when the application runs in the environment.
  • Use the environment variable configuration provider to provide through the environment variable.
  • Use the command line configuration provider to provide through command line parameters.

The source code is as follows:

public static IHostBuilder CreateDefaultBuilder(string[] args)
        {
            var builder = new HostBuilder();

            builder.UseContentRoot(Directory.GetCurrentDirectory());
            builder.ConfigureHostConfiguration(config =>
            {
                config.AddEnvironmentVariables(prefix: "DOTNET_");
                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            });

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

                // IMPORTANT: This needs to be added *before* configuration is loaded, this lets
                // the defaults be overridden by the configuration.
                if (isWindows)
                {
                    // Default the EventLogLoggerProvider to warning or above
                    logging.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning);
                }

                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();

                if (isWindows)
                {
                    // Add the EventLogLoggerProvider on windows machines
                    logging.AddEventLog();
                }
            })
            .UseDefaultServiceProvider((context, options) =>
            {
                var isDevelopment = context.HostingEnvironment.IsDevelopment();
                options.ValidateScopes = isDevelopment;
                options.ValidateOnBuild = isDevelopment;
            });

            return builder;
        }

Source address: https://github.com/dotnet/extensions/blob/release/3.1/src/Hosting/Hosting/src/Host.cs

It can be seen from the code that the priority of configuration obtained by the program is Appsettings json -> appsettings. environment JSON - > environment variables - > command line parameters. We test according to priority.

Create a new console method to return all configuration information. The code is as follows:

private readonly ILogger<HomeController> _logger;

        public IConfiguration _configuration { get; }

        public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        public IActionResult Index()
        {
            return Json(_configuration.AsEnumerable());
        }

First, Appsettings JSON configuration file, as follows:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "WebConfig": {
    "Name": "itsvse.com",
    "Date": "2021"
  }
}

New Appsettings Test. JSON configuration, as follows:

{
  "WebConfig": {
    "Name": "itsvse.com test"
  }
}

Try to start the project and check the configuration of WebConfig:Name and WebConfig:Date, as shown in the following figure:

Locate properties - > launchsettings JSON file, modify aspnetcore_ The environment environment is configured as Test, as follows:

 "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Test"
      }
    }

At this time, the program will read Appsettings Test. JSON configuration, try to restart the project, and find that WebConfig:Name has been overwritten, as shown in the following figure:

Modify launchsettings again JSON file, set the value of WebConfig:Name through the environment variable, and the code is as follows:

"IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Test",
        "WebConfig__Name": "itsvse env"
      }
    }

Note: the environment variable modifies the value of WebConfig:Name, and the variable name is WebConfig__Name (separated by double underline)

Try to restart the project and find that the value of WebConfig:Name has been overwritten by the value set by the environment variable, as shown in the following figure:

Try to modify the value of the default configuration through the command line. Start the command as follows:

dotnet run --WebConfig:Name="itsvse command"

As shown below:

Use practice to test the priority of configuration key values. End.

Topics: .NET