Configuration class Configuration of ASP.NET Core 8

Configuration

Configuration can be set in two ways:

  • The object app.Configuration property created by WebApplication
  • builder.Configuration property created by WebApplicationBuilder

The configuration of the app has a higher priority, and the host Configuration is used as a backup configuration because the app runs on the host.
Each method provides a very rich configuration options, which can be used in various scenarios for use in the development environment and production environment.

Host default variable

These variables are preset when the builder is initialized:

  • Application name
  • Environment name, such as Development, Production, and Staging
  • Content root directory
  • web root directory
  • Indicates whether to scan the DLL to be used for startup
  • Variables to be read by code in App and HostBuilderContext.Configuration in IHostBuilder.ConfigureAppConfiguration callback

The setting items of other hosts are read from the App's Configuration, not from the host's Configuration.
It is read from the host's Configuration only if it is not set in the App's Configuration.

Application configuration provider and prioritization

In order of priority:

  1. Command line startup parameters
  2. Unprefixed environment variables
  3. User secrets in the Development environment
  4. appsettings.{Environment}.json file, such as appsettings.Production.json or appsettings.Development.json
  5. appsettings.json file

The order in which these providers are introduced is opposite to their priority. The following introduces each provider from low to high:

Example appsettings.json file

{
    
    
  "Position": {
    
    
    "Title": "Editor",
    "Name": "Joe Smith"
  },
  "MyKey": "My appsettings.json Value",
  "Logging": {
    
    
    "LogLevel": {
    
    
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

can be read like this:

var myKeyValue = Configuration["MyKey"];
var name = Configuration["Position:Name"];
var defaultLogLevel = Configuration["Logging:LogLevel:Default"];

User Secret

Unprefixed environment variables

Unprefixed environment variables are environment variables without the ASPNETCORE_ or DOTNET_ prefix,
such as "ASPNETCORE_ENVIRONMENT": "Development" in the launchSettings.json file.

Can pass code:

builder.Configuration.AddEnvironmentVariables(prefix: "MyCustomPrefix_");

or from the command line:

setx MyKey "My key from setx Environment" /M
setx Position__Title Environment_Editor /M
setx Position__Name Environment_Rick /M

to set.

Environment variables in launchSettings.json

The environment variables in launchSettings.json will override the system variables set above:

"applicationUrl": "https://localhost:5001;http://localhost:5000"

loop through all environment variables

In order to debug.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
foreach (var c in builder.Configuration.AsEnumerable())
{
    
    
    Console.WriteLine(c.Key + " = " + c.Value);
}

Command line startup parameters

like:

dotnet run MyKey="Using =" Position:Title=Cmd Position:Name=Cmd_Rick

You can also preset the mapping to map the short startup parameters to the original long parameter names:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var switchMappings = new Dictionary<string, string>()
         {
    
    
             {
    
     "-k1", "key1" },
             {
    
     "-k2", "key2" },
             {
    
     "--alt3", "key3" },
             {
    
     "--alt4", "key4" },
             {
    
     "--alt5", "key5" },
             {
    
     "--alt6", "key6" },
         };
builder.Configuration.AddCommandLine(args, switchMappings);
var app = builder.Build();

Then when using the command line:

dotnet run -k1 value1 -k2 value2 --alt3=value2 /alt4=value3 --alt5 value5 /alt6 value6

The value of -k1 is mapped to key1.

You can also set startup parameters through the Debug window of Visual Studio.

database connection prefix

  • CUSTOMCONNSTR_ : from Baoyi provider
  • MYSQLCONNSTR_ MySQLprovider
  • SQLAZURECONNSTR_ :Azure SQL Database
  • SQLCONNSTR_ :SQL Serverprovider

When variables with these prefixes are found in the environment variables, the prefixes will be removed, and then the database connection string will be automatically changed to:
MYSQLCONNSTR_{KEY} --> ConnectionStrings:{KEY}

Then you can read the database provider through config, but there is no database provider for Baoyi provider:
key: ConnectionStrings:{KEY}_ProviderName
value: MySql.Data.MySqlClient

Provider for file configuration

  • INI configuration provider
var builder = WebApplication.CreateBuilder(args);
builder.Configuration
    .AddIniFile("MyIniConfig.ini", optional: true, reloadOnChange: true)
    .AddIniFile($"MyIniConfig.{
      
      builder.Environment.EnvironmentName}.ini",
                optional: true, reloadOnChange: true);
builder.Configuration.AddEnvironmentVariables();
builder.Configuration.AddCommandLine(args);
builder.Services.AddRazorPages();
var app = builder.Build();

Example of an INI file:

MyKey="MyIniConfig.ini Value"

[Position]
Title="My INI Config title"
Name="My INI Config name"

[Logging:LogLevel]
Default=Information
Microsoft=Warning
  • JSON configuration provider
using Microsoft.Extensions.DependencyInjection.ConfigSample.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("MyConfig.json",
        optional: true, //The file is optional
        reloadOnChange: true); //The file is reloaded when changes are saved
builder.Services.AddRazorPages();
var app = builder.Build();

Generally, JSON configuration provider is not used

  • XML configuration provider
var builder = WebApplication.CreateBuilder(args);
builder. Configuration
    .AddXmlFile("MyXMLFile.xml", optional: true, reloadOnChange: true)
    .AddXmlFile($"MyXMLFile.{
      
      builder.Environment.EnvironmentName}.xml",
                optional: true, reloadOnChange: true);
builder.Configuration.AddEnvironmentVariables();
builder.Configuration.AddCommandLine(args);
builder.Services.AddRazorPages();
var app = builder. Build();

Example of XML file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <MyKey>MyXMLFile Value</MyKey>
  <Position>
    <Title>Title from  MyXMLFile</Title>
    <Name>Name from MyXMLFile</Name>
  </Position>
  <Logging>
    <LogLevel>
      <Default>Information</Default>
      <Microsoft>Warning</Microsoft>
    </LogLevel>
  </Logging>
</configuration>

Key-per-file configuration provider

For docker, use a file in a directory as configuration. The key is the file name, and the value is the file content.

builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
    
    
    var path = Path.Combine(
        Directory.GetCurrentDirectory(), "path/to/files");
    config.AddKeyPerFile(directoryPath: path, optional: true);
})

Memory Configuration Provider

var builder = WebApplication.CreateBuilder(args);
var Dict = new Dictionary<string, string>
        {
    
    
           {
    
    "MyKey", "Dictionary MyKey Value"},
           {
    
    "Position:Title", "Dictionary_Title"},
           {
    
    "Position:Name", "Dictionary_Name" },
           {
    
    "Logging:LogLevel:Default", "Warning"}
        };

builder.Configuration.AddInMemoryCollection(Dict);
builder.Configuration.AddEnvironmentVariables();
builder.Configuration.AddCommandLine(args);
builder.Services.AddRazorPages();
var app = builder.Build();

Configure Kestrel's EndPoint

Can be configured in appsettings.json:

{
    
    
  "Kestrel": {
    
    
    "Endpoints": {
    
    
      "Https": {
    
    
        "Url": "https://localhost:9999"
      }
    }
  },
  "Logging": {
    
    
    "LogLevel": {
    
    
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
} 

Access Config from dependency injection

public class Service
{
    
    
    private readonly IConfiguration _config;

    public Service(IConfiguration config) =>
        _config = config;

    public void DoSomething()
    {
    
    
        var configSettingValue = _config["ConfigSetting"];
        // ...
    }
}

Accessing Config from Razor Pages

@page
@model Test5Model
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

Configuration value for 'MyKey': @Configuration["MyKey"]

Access Config from MVC Page

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

Configuration value for 'MyKey': @Configuration["MyKey"]

Access from the Main function

var builder = WebApplication.CreateBuilder(args);
var key1 = builder.Configuration.GetValue<string>("KeyOne");
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
var key2 = app.Configuration.GetValue<int>("KeyTwo");
var key3 = app.Configuration.GetValue<bool>("KeyThree");
app.Logger.LogInformation("KeyOne: {KeyOne}", key1);
app.Logger.LogInformation("KeyTwo: {KeyTwo}", key2);
app.Logger.LogInformation("KeyThree: {KeyThree}", key3);
app.Run();

Host configuration vs App configuration

Before starting and configuring the App, the Host is first configured and started.
Then Host is responsible for starting App and App life cycle management.
Both App and Host use the various providers mentioned above.
Host configuration will also be included in App configuration, but App configuration has a higher priority.

other configuration

  • launch.json/launchSettings.json , for the development environment.
  • web.config is the server configuration file.

Guess you like

Origin blog.csdn.net/cuit/article/details/132544704