Kurse:ASP.NET Core Konfiguration: Unterschied zwischen den Versionen

Aus ahrensburg.city
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 Environments – Spickzettel =
= ASP.NET Core Konfiguration – Spickzettel =


ASP.NET Core verwendet sogenannte '''Environments''' (Umgebungen), um das Verhalten einer Anwendung je nach Bereitstellungsszenario (Development, Staging, Production) anzupassen.
== Grundkonzepte ==
* '''Konfigurationsanbieter''': Laden Konfigurationen aus Quellen (z. B. JSON, Umgebungsvariablen).
* '''Konfigurationsquellen''': Speicherorte (Dateien, Variablen etc.).
* '''Key-Value-Paare''': Konfigurationen als Schlüssel-Wert.


== Übliche Umgebungen ==
== Häufige Quellen ==
* '''JSON-Dateien''':
  Vorteil: Struktur, leicht lesbar. 
  Beispiel:
  <syntaxhighlight lang="json">
  {
    "Logging": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
  </syntaxhighlight>


* '''Development''': Lokale Entwicklungsumgebung – ideal zum Testen und Debugging.
* '''Umgebungsvariablen''':
* '''Staging''': Vorproduktionsumgebung – bildet die Produktion möglichst genau ab.
  Vorteil: Ideal für geheime oder umgebungsspezifische Daten.
* '''Production''': Live-Umgebung für Endnutzer.
  Mapping: `ASPNETCORE_Logging__LogLevel__Default` → `Logging:LogLevel:Default`


== Umgebung setzen ==
* '''User-Secrets (Entwicklung)''':
  Initialisierung:
  <syntaxhighlight lang="bash">
  dotnet user-secrets init
  dotnet user-secrets set "MySecret" "123"
  </syntaxhighlight>


Die Umgebung wird über die Umgebungsvariable '''ASPNETCORE_ENVIRONMENT''' definiert.
* '''Azure Key Vault''': Für sichere Produktionsgeheimnisse.


=== Möglichkeiten zum Setzen ===
== Konfiguration einbinden ==
'''Program.cs'''
<syntaxhighlight lang="csharp">
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;


; '''launchSettings.json'''
builder.Configuration
: Im Ordner ''Properties'' des Projekts:
    .AddJsonFile("appsettings.json", optional: false)
<syntaxhighlight lang="json">
    .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
"environmentVariables": {
    .AddEnvironmentVariables()
  "ASPNETCORE_ENVIRONMENT": "Development"
    .AddUserSecrets<Program>();
}
</syntaxhighlight>
</syntaxhighlight>


; '''Terminal (Windows PowerShell / CMD)'''
== Zugriff auf Konfiguration ==
<syntaxhighlight lang="powershell">
$env:ASPNETCORE_ENVIRONMENT = "Development"
dotnet run
</syntaxhighlight>
<syntaxhighlight lang="cmd">
set ASPNETCORE_ENVIRONMENT=Production
dotnet run
</syntaxhighlight>
 
; '''macOS / Linux'''
<syntaxhighlight lang="bash">
export ASPNETCORE_ENVIRONMENT=Staging
dotnet run
</syntaxhighlight>
 
== Zugriff auf die Umgebung im Code ==
 
=== Program.cs ===
<syntaxhighlight lang="csharp">
<syntaxhighlight lang="csharp">
var builder = WebApplication.CreateBuilder(args);
var port = configuration.GetValue<int>("Server:Port");
var app = builder.Build();
var logLevel = configuration["Logging:LogLevel:Default"];
 
var section = configuration.GetSection("Logging");
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
}
</syntaxhighlight>
</syntaxhighlight>


=== Controller ===
== Injection in Controller/Service ==
<syntaxhighlight lang="csharp">
<syntaxhighlight lang="csharp">
public class HomeController : Controller
public class HomeController : Controller
{
{
     private readonly IWebHostEnvironment _env;
     private readonly IConfiguration _config;


     public HomeController(IWebHostEnvironment env)
     public HomeController(IConfiguration config)
     {
     {
         _env = env;
         _config = config;
     }
     }


     public IActionResult Index()
     public IActionResult Index()
     {
     {
         ViewBag.CurrentEnvironment = _env.EnvironmentName;
         var value = _config["MyKey"];
         return View();
         return View();
     }
     }
Zeile 75: Zeile 72:
</syntaxhighlight>
</syntaxhighlight>


== Konfigurationsdateien ==
== Options Pattern ==
* Vorteile: Starke Typisierung, IntelliSense, Validierung


Erstelle Dateien wie:
'''Beispiel:'''
* ''appsettings.Development.json''
<syntaxhighlight lang="csharp">
* ''appsettings.Staging.json''
// MyOptions.cs
* ''appsettings.Production.json''
public class MyOptions
{
    public string Option1 { get; set; }
    public int Option2 { get; set; }
}


Diese überschreiben Einstellungen aus ''appsettings.json'' je nach aktiver Umgebung.
// Program.cs
builder.Services.Configure<MyOptions>(builder.Configuration.GetSection("MyOptions"));


== <environment> Tag Helper ==
// Service
public class MyService
{
    private readonly IOptions<MyOptions> _options;


In Razor Views:
    public MyService(IOptions<MyOptions> options)
<syntaxhighlight lang="html">
    {
<environment include="Development">
        _options = options;
  <script src="~/scripts/dev.js"></script>
    }
</environment>
}
<environment exclude="Development">
  <script src="~/scripts/prod.min.js"></script>
</environment>
</syntaxhighlight>
</syntaxhighlight>


== Best Practices ==
== 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>


* Nutze '''environment-spezifische Dateien''' für getrennte Konfigurationen.
== Zugriff in Code ==
* Verwende '''verschiedene Middleware-Pipelines''':
<syntaxhighlight lang="csharp">
  <syntaxhighlight lang="csharp">
var env = builder.Environment;
  if (app.Environment.IsProduction())
if (env.IsDevelopment())
      app.UseExceptionHandler("/Error");
{
  </syntaxhighlight>
    app.UseDeveloperExceptionPage();
* '''Logging''' pro Umgebung anpassen.
}
* '''Feature Flags''' über Umgebungsvariablen oder appsettings aktivieren/deaktivieren.
</syntaxhighlight>


== launchSettings.json verstehen ==
== HttpClient (mit IHttpClientFactory) ==
* Registrierung:
<syntaxhighlight lang="csharp">
builder.Services.AddHttpClient("finnhub", client =>
{
    client.BaseAddress = new Uri("https://finnhub.io/api/v1/");
});
</syntaxhighlight>


<syntaxhighlight lang="json">
* Verwendung:
<syntaxhighlight lang="csharp">
public class FinnhubService
{
{
  "profiles": {
    private readonly HttpClient _client;
     "MyApp": {
 
      "commandName": "Project",
    public FinnhubService(IHttpClientFactory factory)
      "environmentVariables": {
     {
         "ASPNETCORE_ENVIRONMENT": "Development"
        _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>


== Interview-Tipps ==
== Best Practices ==
 
* Verwende '''Options Pattern''' für strukturierte Konfiguration.
* Erkläre, warum Environments wichtig sind (z. B. Sicherheit, Flexibilität).
* '''appsettings.{env}.json''' für Umgebungen.
* Zeige, wie man appsettings.{ENV}.json nutzt.
* '''User Secrets''' oder '''Azure Key Vault''' für sensible Daten.
* Beschreibe, wie Middleware sich abhängig von der Umgebung unterscheidet.
* '''reloadOnChange: true''' für dynamische Updates.
* Erkläre, wie man ASPNETCORE_ENVIRONMENT beim Deployment setzt.
* 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.