Outils pour utilisateurs

Outils du site


web:asp.net:core:configuration

Table des matières

Configuration

Exemple simple

Dans le constructeur de Startup.cs:

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables();
this.Configuration = builder.Build();

Le fichier appsettings.json :

{
  "Options": [
    "option1",
    "option2",
    "option3"
  ]
}

La classe MyOptions :

public class MyOptions
{
    public string[] Options { get; set; }
}

Dans le fichier Startup.cs, méthode ConfigureServices:

MyOptions myOptions = new MyOptions();
 
services.Configure<MyOptions>(this.Configuration);
this.Configuration.Bind(myOptions);

Autre exemple:

{
  "Section": {
    "MyOptions": [ "option1", "option2" ]
  }
}
MyOptions myOptions = new MyOptions();
this.Configuration.GetSection("Section").Bind(myOptions);

Autre exemple:

{
  "MyOptions": {
    "Options": [ "option1", "option2" ]
  }
}
services.AddOptions();
 
services.Configure<MyOptions>(this.Configuration.GetSection("MyOptions"));

Dans une classe consommatrice, on peut faire :

public class MyClass
{
    private readonly string[] _myOptions;
 
    public MyClass(IOptions<MyOptions> myOptions)
    {
        this._options = myOptions.Value.Options;
    }
}

Providers

Provider Exemple Notes
appsettings.json { “key”: “value” }
appsettings.{ENVIRONMENT}.json { “key”: “other value” }
User Secrets (Developement) dotnet user-secrets set “key” “development value”
Environment variables Powershell: setx key “environment value”, bash: export key=“environment value”
Command-line arguments dotnet run –key “important value”

L'environnement est lu de DOTNET_ENVIRONMENT ou ASPNETCORE_ENVIRONMENT.

Source: Everything you need to know about configuration and secret management in .NET

web/asp.net/core/configuration.txt · Dernière modification : 2023/11/17 20:09 de sgariepy