Kurse:ASP.NET Core Konfiguration: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
Die Seite wurde neu angelegt: „= ASP.NET Core Environments – Spickzettel = ASP.NET Core verwendet sogenannte '''Environments''' (Umgebungen), um das Verhalten einer Anwendung je nach Bereitstellungsszenario (Development, Staging, Production) anzupassen. == Übliche Umgebungen == * '''Development''': Lokale Entwicklungsumgebung – ideal zum Testen und Debugging. * '''Staging''': Vorproduktionsumgebung – bildet die Produktion möglichst genau ab. * '''Production''': Live-Umgebung…“ |
Keine Bearbeitungszusammenfassung |
||
| Zeile 1: | Zeile 1: | ||
= ASP.NET Core | = 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: | |||
<syntaxhighlight lang="json"> | |||
{ | |||
"Logging": { | |||
"LogLevel": { | |||
"Default": "Information" | |||
} | |||
} | |||
} | |||
</syntaxhighlight> | |||
* ''' | * '''Umgebungsvariablen''': | ||
Vorteil: Ideal für geheime oder umgebungsspezifische Daten. | |||
Mapping: `ASPNETCORE_Logging__LogLevel__Default` → `Logging:LogLevel:Default` | |||
= | * '''User-Secrets (Entwicklung)''': | ||
Initialisierung: | |||
<syntaxhighlight lang="bash"> | |||
dotnet user-secrets init | |||
dotnet user-secrets set "MySecret" "123" | |||
</syntaxhighlight> | |||
* '''Azure Key Vault''': Für sichere Produktionsgeheimnisse. | |||
=== | == Konfiguration einbinden == | ||
'''Program.cs''' | |||
<syntaxhighlight lang="csharp"> | |||
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>(); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== Zugriff auf Konfiguration == | |||
== Zugriff auf | |||
<syntaxhighlight lang="csharp"> | <syntaxhighlight lang="csharp"> | ||
var | var port = configuration.GetValue<int>("Server:Port"); | ||
var | var logLevel = configuration["Logging:LogLevel:Default"]; | ||
var section = configuration.GetSection("Logging"); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== | == Injection in Controller/Service == | ||
<syntaxhighlight lang="csharp"> | <syntaxhighlight lang="csharp"> | ||
public class HomeController : Controller | public class HomeController : Controller | ||
{ | { | ||
private readonly | private readonly IConfiguration _config; | ||
public HomeController( | public HomeController(IConfiguration config) | ||
{ | { | ||
_config = config; | |||
} | } | ||
public IActionResult Index() | public IActionResult Index() | ||
{ | { | ||
var value = _config["MyKey"]; | |||
return View(); | return View(); | ||
} | } | ||
| Zeile 75: | Zeile 72: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== | == Options Pattern == | ||
* Vorteile: Starke Typisierung, IntelliSense, Validierung | |||
'''Beispiel:''' | |||
<syntaxhighlight lang="csharp"> | |||
// 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; | |||
} | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== | == Hierarchische Konfiguration == | ||
'''Beispiel (JSON):''' | |||
<syntaxhighlight lang="json"> | |||
{ | |||
"Inventory": { | |||
"StockAlertThreshold": 20, | |||
"WarehouseLocations": [ "New York", "London" ] | |||
} | |||
} | |||
</syntaxhighlight> | |||
'''Zugriff:''' | |||
<syntaxhighlight lang="csharp"> | |||
var threshold = configuration.GetValue<int>("Inventory:StockAlertThreshold"); | |||
var locations = configuration.GetSection("Inventory:WarehouseLocations").Get<string[]>(); | |||
</syntaxhighlight> | |||
== Umgebungsspezifische Konfiguration == | |||
* `appsettings.{Environment}.json` z. B.: | |||
- appsettings.Development.json | |||
- appsettings.Production.json | |||
== Umgebungsvariable setzen == | |||
<syntaxhighlight lang="bash"> | |||
# Bash | |||
export ASPNETCORE_Logging__LogLevel__Default="Debug" | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="powershell"> | |||
# PowerShell | |||
$env:ASPNETCORE_Logging__LogLevel__Default = "Debug" | |||
</syntaxhighlight> | |||
== Zugriff in Code == | |||
<syntaxhighlight lang="csharp"> | |||
var env = builder.Environment; | |||
if (env.IsDevelopment()) | |||
{ | |||
app.UseDeveloperExceptionPage(); | |||
} | |||
</syntaxhighlight> | |||
== | == HttpClient (mit IHttpClientFactory) == | ||
* Registrierung: | |||
<syntaxhighlight lang="csharp"> | |||
builder.Services.AddHttpClient("finnhub", client => | |||
{ | |||
client.BaseAddress = new Uri("https://finnhub.io/api/v1/"); | |||
}); | |||
</syntaxhighlight> | |||
<syntaxhighlight lang=" | * Verwendung: | ||
<syntaxhighlight lang="csharp"> | |||
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(); | |||
} | } | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== | == 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. | ||
Aktuelle Version vom 29. Juni 2025, 20:06 Uhr
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.