Kurse:ASP.NET Core Konfiguration
ASP.NET Core Konfiguration – Spickzettel
Grundkonzepte
- Konfigurationsanbieter: Laden Konfigurationen aus Quellen (z. B. JSON, Umgebungsvariablen).
- Konfigurationsquellen: Speicherorte (Dateien, Variablen etc.).
- Key-Value-Paare: Konfigurationen als Schlüssel-Wert.
Häufige Quellen
- JSON-Dateien:
Vorteil: Struktur, leicht lesbar. Beispiel:
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
}
}
- Umgebungsvariablen:
Vorteil: Ideal für geheime oder umgebungsspezifische Daten. Mapping: `ASPNETCORE_Logging__LogLevel__Default` → `Logging:LogLevel:Default`
- User-Secrets (Entwicklung):
Initialisierung:
dotnet user-secrets init
dotnet user-secrets set "MySecret" "123"
- Azure Key Vault: Für sichere Produktionsgeheimnisse.
Konfiguration einbinden
Program.cs
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
builder.Configuration
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.AddUserSecrets<Program>();
Zugriff auf Konfiguration
var port = configuration.GetValue<int>("Server:Port");
var logLevel = configuration["Logging:LogLevel:Default"];
var section = configuration.GetSection("Logging");
Injection in Controller/Service
public class HomeController : Controller
{
private readonly IConfiguration _config;
public HomeController(IConfiguration config)
{
_config = config;
}
public IActionResult Index()
{
var value = _config["MyKey"];
return View();
}
}
Options Pattern
- Vorteile: Starke Typisierung, IntelliSense, Validierung
Beispiel:
// MyOptions.cs
public class MyOptions
{
public string Option1 { get; set; }
public int Option2 { get; set; }
}
// Program.cs
builder.Services.Configure<MyOptions>(builder.Configuration.GetSection("MyOptions"));
// Service
public class MyService
{
private readonly IOptions<MyOptions> _options;
public MyService(IOptions<MyOptions> options)
{
_options = options;
}
}
Hierarchische Konfiguration
Beispiel (JSON):
{
"Inventory": {
"StockAlertThreshold": 20,
"WarehouseLocations": [ "New York", "London" ]
}
}
Zugriff:
var threshold = configuration.GetValue<int>("Inventory:StockAlertThreshold");
var locations = configuration.GetSection("Inventory:WarehouseLocations").Get<string[]>();
Umgebungsspezifische Konfiguration
- `appsettings.{Environment}.json` z. B.:
- appsettings.Development.json - appsettings.Production.json
Umgebungsvariable setzen
# Bash
export ASPNETCORE_Logging__LogLevel__Default="Debug"
# PowerShell
$env:ASPNETCORE_Logging__LogLevel__Default = "Debug"
Zugriff in Code
var env = builder.Environment;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
HttpClient (mit IHttpClientFactory)
- Registrierung:
builder.Services.AddHttpClient("finnhub", client =>
{
client.BaseAddress = new Uri("https://finnhub.io/api/v1/");
});
- Verwendung:
public class FinnhubService
{
private readonly HttpClient _client;
public FinnhubService(IHttpClientFactory factory)
{
_client = factory.CreateClient("finnhub");
}
public async Task<string> GetQuote()
{
var response = await _client.GetAsync("quote?symbol=AAPL&token=API_KEY");
return await response.Content.ReadAsStringAsync();
}
}
Best Practices
- Verwende Options Pattern für strukturierte Konfiguration.
- appsettings.{env}.json für Umgebungen.
- User Secrets oder Azure Key Vault für sensible Daten.
- reloadOnChange: true für dynamische Updates.
- Kombiniere mehrere Quellen mit klarer Priorität.