Verwenden von mehreren Umgebungen in ASP.NET CoreUse multiple environments in ASP.NET Core
Von Rick Anderson und Kirk LarkinBy Rick Anderson and Kirk Larkin
ASP.NET Core konfiguriert das App-Verhalten basierend auf der Laufzeitumgebung mit einer Umgebungsvariablen.ASP.NET Core configures app behavior based on the runtime environment using an environment variable.
Anzeigen oder Herunterladen von Beispielcode (Vorgehensweise zum Herunterladen)View or download sample code (how to download)
UmgebungenEnvironments
ASP.NET Core liest zur Bestimmung der Laufzeitumgebung aus den folgenden Umgebungsvariablen:To determine the runtime environment, ASP.NET Core reads from the following environment variables:
- DOTNET_ENVIRONMENTDOTNET_ENVIRONMENT
ASPNETCORE_ENVIRONMENT
, bei Aufruf von ConfigureWebHostDefaults.ASPNETCORE_ENVIRONMENT
when ConfigureWebHostDefaults is called.ConfigureWebHostDefaults
wird von den Standardvorlagen der ASP.NET Core-Web-App aufgerufen.The default ASP.NET Core web app templates callConfigureWebHostDefaults
.DOTNET_ENVIRONMENT
wird vomASPNETCORE_ENVIRONMENT
-Wert überschrieben.TheASPNETCORE_ENVIRONMENT
value overridesDOTNET_ENVIRONMENT
.
IHostEnvironment.EnvironmentName
kann auf einen beliebigen Wert festgelegt werden, das Framework stellt allerdings die folgenden Werte bereit:IHostEnvironment.EnvironmentName
can be set to any value, but the following values are provided by the framework:
- Development : Mit der Datei launchSettings.json wird
ASPNETCORE_ENVIRONMENT
auf dem lokalen Computer aufDevelopment
festgelegt.Development : The launchSettings.json file setsASPNETCORE_ENVIRONMENT
toDevelopment
on the local machine. - Staging
- Production : Der Standardwert, wenn
DOTNET_ENVIRONMENT
undASPNETCORE_ENVIRONMENT
nicht festgelegt wurden.Production : The default ifDOTNET_ENVIRONMENT
andASPNETCORE_ENVIRONMENT
have not been set.
Der folgende CodeThe following code:
- Ruft UseDeveloperExceptionPage auf, wenn
ASPNETCORE_ENVIRONMENT
aufDevelopment
festgelegt ist.Calls UseDeveloperExceptionPage whenASPNETCORE_ENVIRONMENT
is set toDevelopment
. - ruft UseExceptionHandler auf, wenn der Wert von
ASPNETCORE_ENVIRONMENT
aufStaging
,Production
oderStaging_2
festgelegt ist.Calls UseExceptionHandler when the value ofASPNETCORE_ENVIRONMENT
is set toStaging
,Production
, orStaging_2
. - fügt IWebHostEnvironment in
Startup.Configure
ein.Injects IWebHostEnvironment intoStartup.Configure
. Diese Vorgehensweise ist nützlich, wenn die AppStartup.Configure
nur für einige Umgebungen mit minimalen Codeunterschieden pro Umgebung anpassen muss.This approach is useful when the app only requires adjustingStartup.Configure
for a few environments with minimal code differences per environment. - ähnelt dem von den ASP.NET Core-Vorlagen generierten Code.Is similar to the code generated by the ASP.NET Core templates.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
if (env.IsProduction() || env.IsStaging() || env.IsEnvironment("Staging_2"))
{
app.UseExceptionHandler("/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
Das Hilfsprogramm für Umgebungstags verwendet den Wert von IHostEnvironment.EnvironmentName zum Einschließen oder Ausschließen von Markup im Element:The Environment Tag Helper uses the value of IHostEnvironment.EnvironmentName to include or exclude markup in the element:
<environment include="Development">
<div>The effective tag is: <environment include="Development"></div>
</environment>
<environment exclude="Development">
<div>The effective tag is: <environment exclude="Development"></div>
</environment>
<environment include="Staging,Development,Staging_2">
<div>
The effective tag is:
<environment include="Staging,Development,Staging_2">
</div>
</environment>
Die Infoseite des Beispielcodes enthält das vorangehende Markup und zeigt den Wert von IWebHostEnvironment.EnvironmentName
an.The About page from the sample code includes the preceding markup and displays the value of IWebHostEnvironment.EnvironmentName
.
Unter Windows und macOS wird bei Umgebungsvariablen und Werten die Groß-/Kleinschreibung nicht beachtet.On Windows and macOS, environment variables and values aren't case-sensitive. Bei Linux-Umgebungsvariablen und -Werten wird die Groß-/Kleinschreibung standardmäßig beachtet.Linux environment variables and values are case-sensitive by default.
Erstellen von „EnvironmentsSample“Create EnvironmentsSample
Der in diesem Artikel verwendete Beispielcode basiert auf einem Razor Pages-Projekt namens EnvironmentsSample.The sample code used in this document is based on a Razor Pages project named EnvironmentsSample.
Mit dem folgenden Code wird eine Web-App mit dem Namen EnvironmentsSample erstellt und ausgeführt:The following code creates and runs a web app named EnvironmentsSample:
dotnet new webapp -o EnvironmentsSample
cd EnvironmentsSample
dotnet run --verbosity normal
Wenn die App ausgeführt wird, wird eine Ausgabe ähnlich der folgenden angezeigt:When the app runs, it displays some of the following output:
Using launch settings from c:\tmp\EnvironmentsSample\Properties\launchSettings.json
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: c:\tmp\EnvironmentsSample
Entwicklung und die Datei „launchSettings.json“Development and launchSettings.json
In der Entwicklungsumgebung können Features aktiviert werden, die in der Produktion nicht verfügbar gemacht werden sollten.The development environment can enable features that shouldn't be exposed in production. Mit den ASP.NET Core-Vorlagen wird beispielsweise die Seite mit Ausnahmen für Entwickler in der Entwicklungsumgebung aktiviert.For example, the ASP.NET Core templates enable the Developer Exception Page in the development environment.
Die Umgebung für die Entwicklung lokaler Computer kann in der Datei Properties\launchSettings.json des Projekts festgelegt werden.The environment for local machine development can be set in the Properties\launchSettings.json file of the project. Mit in der Datei launchSettings.json festgelegten Umgebungsvariablen werden in der Systemumgebung festgelegte Werte überschrieben.Environment values set in launchSettings.json override values set in the system environment.
Die Datei launchSettings.jsonThe launchSettings.json file:
- wird nur auf dem lokalen Entwicklungscomputer verwendet.Is only used on the local development machine.
- wird nicht bereitgestellt.Is not deployed.
- enthält Profileinstellungen.contains profile settings.
Der folgende JSON-Code zeigt die Datei launchSettings.json für ein ASP.NET Core-Webprojekt mit dem Namen EnvironmentsSample, das mit Visual Studio oder dotnet new
erstellt wurde:The following JSON shows the launchSettings.json file for an ASP.NET Core web projected named EnvironmentsSample created with Visual Studio or dotnet new
:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:64645",
"sslPort": 44366
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"EnvironmentsSample": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Das vorangehende Markup enthält zwei Profile:The preceding markup contains two profiles:
IIS Express
: Das Standardprofil, das beim Starten der App in Visual Studio verwendet wird.IIS Express
: The default profile used when launching the app from Visual Studio. Da der Schlüssel"commandName"
den Wert"IISExpress"
besitzt, wird der Webserver IISExpress verwendet.The"commandName"
key has the value"IISExpress"
, therefore, IISExpress is the web server. Sie können das Startprofil auf das Projekt oder ein beliebiges anderes Profil festlegen.You can set the launch profile to the project or any other profile included. In der folgenden Abbildung wird etwa durch Auswählen des Projektnamens der Kestrel-Webserver gestartet.For example, in the image below, selecting the project name launches the Kestrel web server.EnvironmentsSample
: Der Profilname entspricht dem Projektnamen.EnvironmentsSample
: The profile name is the project name. Dies ist das Standardprofil beim Starten der App mitdotnet run
.This profile is used by default when launching the app withdotnet run
. Da der Schlüssel"commandName"
den Wert"Project"
besitzt, wird der Kestrel-Webserver gestartet.The"commandName"
key has the value"Project"
, therefore, the Kestrel web server is launched.
Mit dem Wert von commandName
wird der zu startende Webserver angegeben.The value of commandName
can specify the web server to launch. commandName
kann einer der folgenden sein:commandName
can be any one of the following:
IISExpress
: Es wird IIS Express gestartet.IISExpress
: Launches IIS Express.IIS
: Es wird kein Webserver gestartet.IIS
: No web server launched. Die Verfügbarkeit von IIS wird erwartet.IIS is expected to be available.Project
: Es wird Kestrel gestartet.Project
: Launches Kestrel.
Auf der Registerkarte Debuggen der Visual Studio-Projekteigenschaften wird eine grafische Benutzeroberfläche für die Bearbeitung der Datei launchSettings.json bereitgestellt.The Visual Studio project properties Debug tab provides a GUI to edit the launchSettings.json file. An Projektprofilen vorgenommene Änderungen werden möglicherweise erst nach einem Neustart des Webservers wirksam.Changes made to project profiles may not take effect until the web server is restarted. Kestrel muss neu gestartet werden, bevor es an der Umgebung vorgenommene Änderungen erkennen kann.Kestrel must be restarted before it can detect changes made to its environment.
Die folgende launchSettings.json-Datei enthält mehrere Profile:The following launchSettings.json file contains multiple profiles:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:64645",
"sslPort": 44366
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IISX-Production": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
},
"IISX-Staging": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Staging",
"ASPNETCORE_DETAILEDERRORS": "1",
"ASPNETCORE_SHUTDOWNTIMEOUTSECONDS": "3"
}
},
"EnvironmentsSample": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"KestrelStaging": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Staging"
}
}
}
}
Profile können auf folgende Weise ausgewählt werden:Profiles can be selected:
Über die Visual Studio-Benutzeroberfläche.From the Visual Studio UI.
Durch Verwenden des Befehls
dotnet run
in einer Befehlsshell, bei dem die Option--launch-profile
auf den Profilnamen festgelegt ist.Using thedotnet run
command in a command shell with the--launch-profile
option set to the profile's name. Bei dieser Vorgehensweise werden nur Kestrel-Profile unterstützt.This approach only supports Kestrel profiles.dotnet run --launch-profile "SampleApp"
Warnung
In der Datei launchSettings.json sollten keine geheimen Schlüssel gespeichert werden.launchSettings.json shouldn't store secrets. Mit dem Secret Manager-Tool können geheime Schlüssel für die lokale Umgebung gespeichert werden.The Secret Manager tool can be used to store secrets for local development.
Wenn Sie Visual Studio Code verwenden, können Umgebungsvariablen in der Datei .vscode/launch.json festgelegt werden.When using Visual Studio Code, environment variables can be set in the .vscode/launch.json file. Im folgenden Beispiel werden mehrere Umgebungsvariablen für Hostkonfigurationswerte festgelegt:The following example sets several Host configuration values environment variables:
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
// Configuration ommitted for brevity.
"env": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "https://localhost:5001",
"ASPNETCORE_DETAILEDERRORS": "1",
"ASPNETCORE_SHUTDOWNTIMEOUTSECONDS": "3"
},
// Configuration ommitted for brevity.
Die Datei .vscode/launch.json wird nur von Visual Studio Code verwendet.The .vscode/launch.json file is only used by Visual Studio Code.
ProduktionProduction
Die Produktionsumgebung sollte so konfiguriert werden, dass eine maximale Sicherheit, Leistung und Stabilität der App erreicht werden.The production environment should be configured to maximize security, performance, and application robustness. Allgemeine Einstellungen, die sich von der Entwicklung unterscheiden, sind zum Beispiel:Some common settings that differ from development include:
- Zwischenspeichern.Caching.
- Clientseitige Ressourcen werden gebündelt, verkleinert und potenziell von einem CDN bedient.Client-side resources are bundled, minified, and potentially served from a CDN.
- Seiten zur Fehlerdiagnose sind deaktiviert.Diagnostic error pages disabled.
- Angezeigte Fehlerseiten sind aktiviert.Friendly error pages enabled.
- Die Produktionsprotokollierung und -überwachung sind aktiviert.Production logging and monitoring enabled. Beispiel: Application Insights.For example, using Application Insights.
Festlegen der UmgebungSet the environment
Häufig ist es sinnvoll, mit einer Umgebungsvariablen oder Plattformeinstellung eine bestimmte Umgebung für Tests festzulegen.It's often useful to set a specific environment for testing with an environment variable or platform setting. Wenn die Umgebung nicht festgelegt ist, wird Production
als Standardwert verwendet, wodurch die meisten Debugfeatures deaktiviert werden.If the environment isn't set, it defaults to Production
, which disables most debugging features. Welche Methode zum Festlegen der Umgebung verwendet wird, hängt vom Betriebssystem ab.The method for setting the environment depends on the operating system.
Wenn der Host erstellt wird, bestimmt die letzte von der App gelesene Umgebungseinstellung die Umgebung der App.When the host is built, the last environment setting read by the app determines the app's environment. Die Umgebung der App kann nicht geändert werden, während die App ausgeführt wird.The app's environment can't be changed while the app is running.
Auf der Infoseite des Beispielcodes wird der Wert von IWebHostEnvironment.EnvironmentName
angezeigt.The About page from the sample code displays the value of IWebHostEnvironment.EnvironmentName
.
Azure App ServiceAzure App Service
Führen Sie die folgenden Schritte durch, um die Umgebung in Azure App Service festzulegen:To set the environment in Azure App Service, perform the following steps:
- Wählen Sie die App auf dem Blatt App Services aus.Select the app from the App Services blade.
- Wählen Sie in der Gruppe Einstellungen das Blatt Konfiguration aus.In the Settings group, select the Configuration blade.
- Wählen Sie auf der Registerkarte Anwendungseinstellungen Neue Anwendungseinstellung aus.In the Application settings tab, select New application setting.
- Geben Sie im Fenster Anwendungseinstellung hinzufügen/bearbeiten
ASPNETCORE_ENVIRONMENT
als Namen an.In the Add/Edit application setting window, provideASPNETCORE_ENVIRONMENT
for the Name. Geben Sie als Wert die Umgebung ein (beispielsweiseStaging
).For Value, provide the environment (for example,Staging
). - Aktivieren Sie das Kontrollkästchen Bereitstellungssloteinstellung, wenn Sie möchten, dass die Umgebungseinstellung im aktuellen Slot bleibt, wenn Bereitstellungsslots getauscht werden.Select the Deployment slot setting check box if you wish the environment setting to remain with the current slot when deployment slots are swapped. Weitere Informationen finden Sie unter Einrichten von Stagingumgebungen in Azure App Service in der Azure-Dokumentation.For more information, see Set up staging environments in Azure App Service in the Azure documentation.
- Wählen Sie OK aus, um das Fenster Anwendungseinstellung hinzufügen/bearbeiten zu schließen.Select OK to close the Add/Edit application setting window.
- Klicken Sie oben auf dem Blatt Konfiguration auf Speichern.Select Save at the top of the Configuration blade.
Azure App Service startet die App automatisch neu, nachdem eine App-Einstellung im Azure-Portal hinzugefügt, geändert oder gelöscht wurde.Azure App Service automatically restarts the app after an app setting is added, changed, or deleted in the Azure portal.
WindowsWindows
Umgebungsvariablen in der Datei launchSettings.json überschreiben in der Systemumgebung festgelegte Werte.Environment values in launchSettings.json override values set in the system environment.
Zum Festlegen der ASPNETCORE_ENVIRONMENT
für die aktuelle Sitzung werden folgende Befehle verwendet, wenn die App mit dotnet run gestartet wird:To set the ASPNETCORE_ENVIRONMENT
for the current session when the app is started using dotnet run, the following commands are used:
EingabeaufforderungCommand prompt
set ASPNETCORE_ENVIRONMENT=Staging
dotnet run --no-launch-profile
PowerShellPowerShell
$Env:ASPNETCORE_ENVIRONMENT = "Staging"
dotnet run --no-launch-profile
Der vorangehende Befehl legt ASPNETCORE_ENVIRONMENT
nur für Prozesse fest, die von diesem Befehlsfenster aus gestartet werden.The preceding command sets ASPNETCORE_ENVIRONMENT
only for processes launched from that command window.
Wenn Sie den Wert in Windows global festlegen möchten, nutzen Sie eine der folgenden Möglichkeiten:To set the value globally in Windows, use either of the following approaches:
Öffnen Sie Systemsteuerung > System > Erweiterte Systemeinstellungen, und fügen Sie den Wert
ASPNETCORE_ENVIRONMENT
hinzu, oder bearbeiten Sie ihn:Open the Control Panel > System > Advanced system settings and add or edit theASPNETCORE_ENVIRONMENT
value:Führen Sie die Eingabeaufforderung als Administrator aus, und verwenden Sie den Befehl
setx
. Alternativ können Sie auch die PowerShell-Eingabeaufforderung als Administrator ausführen und[Environment]::SetEnvironmentVariable
nutzen:Open an administrative command prompt and use thesetx
command or open an administrative PowerShell command prompt and use[Environment]::SetEnvironmentVariable
:EingabeaufforderungCommand prompt
setx ASPNETCORE_ENVIRONMENT Staging /M
Mit dem Parameter
/M
wird angegeben, dass die Umgebungsvariable auf Systemebene festgelegt wird.The/M
switch indicates to set the environment variable at the system level. Ohne den Parameter/M
wird die Umgebungsvariable für das Nutzerkonto festgelegt.If the/M
switch isn't used, the environment variable is set for the user account.PowerShellPowerShell
[Environment]::SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Staging", "Machine")
Mit dem Optionswert
Machine
wird angegeben, dass die Umgebungsvariable auf Systemebene festgelegt wird.TheMachine
option value indicates to set the environment variable at the system level. Verwenden Sie stattdessen den OptionswertUser
, wird die Umgebungsvariable für das Nutzerkonto festgelegt.If the option value is changed toUser
, the environment variable is set for the user account.
Sobald die Umgebungsvariable ASPNETCORE_ENVIRONMENT
global festgelegt wird, gilt sie in jedem geöffneten Befehlsfenster für dotnet run
.When the ASPNETCORE_ENVIRONMENT
environment variable is set globally, it takes effect for dotnet run
in any command window opened after the value is set. Umgebungsvariablen in der Datei launchSettings.json überschreiben in der Systemumgebung festgelegte Werte.Environment values in launchSettings.json override values set in the system environment.
web.configweb.config
Eine Anleitung zum Festlegen der Umgebungsvariable ASPNETCORE_ENVIRONMENT
mit web.config finden Sie im Abschnitt Festlegen von Umgebungsvariablen der im Artikel zu ASP.NET Core-Modul.To set the ASPNETCORE_ENVIRONMENT
environment variable with web.config, see the Setting environment variables section of ASP.NET Core-Modul.
Projektdatei oder VeröffentlichungsprofilProject file or publish profile
Für Windows IIS-Bereitstellungen: Beziehen Sie die <EnvironmentName>
-Eigenschaft in das Veröffentlichungsprofil (PUBXML) oder die Projektdatei ein.For Windows IIS deployments: Include the <EnvironmentName>
property in the publish profile (.pubxml) or project file. Dieser Ansatz legt die Umgebung in web.config fest, wenn das Projekt veröffentlicht wird:This approach sets the environment in web.config when the project is published:
<PropertyGroup>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
Pro IIS-AnwendungspoolPer IIS Application Pool
Wenn Sie für eine App, die in einem isolierten Anwendungspool ausgeführt wird, die Umgebungsvariable ASPNETCORE_ENVIRONMENT
festlegen möchten (unterstützt in IIS 10.0 oder höher), lesen Sie den Abschnitt AppCmd.exe command (Befehl „AppCmd.exe“) im Artikel zu Umgebungsvariablen<environmentVariables>.To set the ASPNETCORE_ENVIRONMENT
environment variable for an app running in an isolated Application Pool (supported on IIS 10.0 or later), see the AppCmd.exe command section of the Environment Variables <environmentVariables> topic. Wurde die Umgebungsvariable ASPNETCORE_ENVIRONMENT
für einen Anwendungspool festgelegt, überschreibt der Wert die Einstellung auf Systemebene.When the ASPNETCORE_ENVIRONMENT
environment variable is set for an app pool, its value overrides a setting at the system level.
Wenn Sie eine APP in den IIS hosten und die Umgebungsvariable ASPNETCORE_ENVIRONMENT
hinzufügen oder ändern, sorgen Sie auf eine der folgenden Arten und Weisen dafür, dass der neue Wert in den Apps hinterlegt ist:When hosting an app in IIS and adding or changing the ASPNETCORE_ENVIRONMENT
environment variable, use any one of the following approaches to have the new value picked up by apps:
- Führen Sie in einer Eingabeaufforderung
net stop was /y
gefolgt vonnet start w3svc
aus.Executenet stop was /y
followed bynet start w3svc
from a command prompt. - Starten Sie den Server neu.Restart the server.
macOSmacOS
Das Festlegen der aktuellen Umgebung für macOS kann inline während der Ausführung der App erfolgen:Setting the current environment for macOS can be performed in-line when running the app:
ASPNETCORE_ENVIRONMENT=Staging dotnet run
Legen Sie die Umgebung alternativ mit export
vor der Ausführung der App fest:Alternatively, set the environment with export
prior to running the app:
export ASPNETCORE_ENVIRONMENT=Staging
Umgebungsvariablen auf Computerebene werden in der BASHRC- oder BASH_PROFILE-Datei festgelegt.Machine-level environment variables are set in the .bashrc or .bash_profile file. Bearbeiten Sie die Datei mit einem beliebigen Text-Editor.Edit the file using any text editor. Fügen Sie die folgende Anweisung hinzu:Add the following statement:
export ASPNETCORE_ENVIRONMENT=Staging
LinuxLinux
Verwenden Sie bei Linux-Distributionen für sitzungsbasierte Variableneinstellungen den Befehl export
in der Eingabeaufforderung und die Datei bash_profile für Umgebungseinstellungen auf Computerebene.For Linux distributions, use the export
command at a command prompt for session-based variable settings and bash_profile file for machine-level environment settings.
Festlegen der Umgebung im CodeSet the environment in code
Rufen Sie beim Erstellen des Hosts UseEnvironment auf.Call UseEnvironment when building the host. Siehe Generischer .NET-Host in ASP.NET Core.See Generischer .NET-Host in ASP.NET Core.
Konfiguration nach UmgebungConfiguration by environment
Informationen zum Laden der Konfiguration nach Umgebung finden Sie unter Konfiguration in ASP.NET Core.To load configuration by environment, see Konfiguration in ASP.NET Core.
Umgebungsbasierte Startklasse und MethodenEnvironment-based Startup class and methods
Einfügen von IWebHostEnvironment in die StartklasseInject IWebHostEnvironment into the Startup class
Fügen Sie IWebHostEnvironment in den Startup
-Konstruktor ein.Inject IWebHostEnvironment into the Startup
constructor. Diese Vorgehensweise ist nützlich, wenn die App Startup
nur für einige Umgebungen mit minimalen Codeunterschieden pro Umgebung konfigurieren muss.This approach is useful when the app requires configuring Startup
for only a few environments with minimal code differences per environment.
Im folgenden Beispiel:In the following example:
- Die Umgebung wird im Feld
_env
gespeichert.The environment is held in the_env
field. _env
wird inConfigureServices
undConfigure
verwendet, um die Startkonfiguration basierend auf der Umgebung der App anzuwenden._env
is used inConfigureServices
andConfigure
to apply startup configuration based on the app's environment.
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
_env = env;
}
public IConfiguration Configuration { get; }
private readonly IWebHostEnvironment _env;
public void ConfigureServices(IServiceCollection services)
{
if (_env.IsDevelopment())
{
Console.WriteLine(_env.EnvironmentName);
}
else if (_env.IsStaging())
{
Console.WriteLine(_env.EnvironmentName);
}
else
{
Console.WriteLine("Not dev or staging");
}
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app)
{
if (_env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
Konventionen der Startup-KlasseStartup class conventions
Nach dem Start einer ASP.NET Core-App lädt die Startklasse die App.When an ASP.NET Core app starts, the Startup class bootstraps the app. Die App kann je nach Umgebung mehrere Startup
-Klassen definieren.The app can define multiple Startup
classes for different environments. Die entsprechende Startup
-Klasse wird zur Laufzeit ausgewählt.The appropriate Startup
class is selected at runtime. Die Klasse, deren Namenssuffix mit der aktuellen Umgebung übereinstimmt, wird priorisiert.The class whose name suffix matches the current environment is prioritized. Ist keine übereinstimmende Startup{EnvironmentName}
-Klasse vorhanden, wird die Klasse Startup
verwendet.If a matching Startup{EnvironmentName}
class isn't found, the Startup
class is used. Diese Vorgehensweise ist nützlich, wenn die App „Startup“ für mehrere Umgebungen mit vielen Codeunterschieden pro Umgebung konfigurieren muss.This approach is useful when the app requires configuring startup for several environments with many code differences per environment. Für typische Apps ist diese Vorgehensweise nicht erforderlich.Typical apps will not need this approach.
Wenn Sie umgebungsbasierte Startup
-Klassen implementieren möchten, erstellen Sie eine Startup{EnvironmentName}
-Klasse und eine Fallback-Klasse vom Typ Startup
:To implement environment-based Startup
classes, create a Startup{EnvironmentName}
classes and a fallback Startup
class:
public class StartupDevelopment
{
public StartupDevelopment(IConfiguration configuration)
{
Configuration = configuration;
Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType.Name);
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
public class StartupProduction
{
public StartupProduction(IConfiguration configuration)
{
Configuration = configuration;
Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType.Name);
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app)
{
app.UseExceptionHandler("/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType.Name);
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
Verwenden Sie die Überladung UseStartup(IWebHostBuilder, String), die einen Assemblynamen akzeptiert:Use the UseStartup(IWebHostBuilder, String) overload that accepts an assembly name:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var assemblyName = typeof(Startup).GetTypeInfo().Assembly.FullName;
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup(assemblyName);
});
}
}
Konventionen der Methode „Start“Startup method conventions
Configure und ConfigureServices unterstützen umgebungsspezifische Versionen der Form Configure<EnvironmentName>
und Configure<EnvironmentName>Services
.Configure and ConfigureServices support environment-specific versions of the form Configure<EnvironmentName>
and Configure<EnvironmentName>Services
. Diese Vorgehensweise eignet sich für Apps, bei denen Startoptionen für mehrere Umgebungen mit vielen Codeunterschieden pro Umgebung konfiguriert werden müssen:This approach is useful when the app requires configuring startup for several environments with many code differences per environment:
public class Startup
{
private void StartupConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void ConfigureDevelopmentServices(IServiceCollection services)
{
MyTrace.TraceMessage();
StartupConfigureServices(services);
}
public void ConfigureStagingServices(IServiceCollection services)
{
MyTrace.TraceMessage();
StartupConfigureServices(services);
}
public void ConfigureProductionServices(IServiceCollection services)
{
MyTrace.TraceMessage();
StartupConfigureServices(services);
}
public void ConfigureServices(IServiceCollection services)
{
MyTrace.TraceMessage();
StartupConfigureServices(services);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
MyTrace.TraceMessage();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
public void ConfigureStaging(IApplicationBuilder app, IWebHostEnvironment env)
{
MyTrace.TraceMessage();
app.UseExceptionHandler("/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
public static class MyTrace
{
public static void TraceMessage([CallerMemberName] string memberName = "")
{
Console.WriteLine($"Method: {memberName}");
}
}
Zusätzliche RessourcenAdditional resources
Von Rick AndersonBy Rick Anderson
ASP.NET Core konfiguriert das App-Verhalten basierend auf der Laufzeitumgebung mit einer Umgebungsvariablen.ASP.NET Core configures app behavior based on the runtime environment using an environment variable.
Anzeigen oder Herunterladen von Beispielcode (Vorgehensweise zum Herunterladen)View or download sample code (how to download)
UmgebungenEnvironments
ASP.NET Core liest die Umgebungsvariable ASPNETCORE_ENVIRONMENT
beim Start der App und speichert diesen Wert unter IHostingEnvironment.EnvironmentName.ASP.NET Core reads the environment variable ASPNETCORE_ENVIRONMENT
at app startup and stores the value in IHostingEnvironment.EnvironmentName. ASPNETCORE_ENVIRONMENT
kann auf einen beliebigen Wert festgelegt werden, das Framework stellt allerdings nur drei Werte bereit:ASPNETCORE_ENVIRONMENT
can be set to any value, but three values are provided by the framework:
- Development
- Staging
- Production (Standardwert)Production (default)
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
if (env.IsProduction() || env.IsStaging() || env.IsEnvironment("Staging_2"))
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseMvc();
}
Der vorangehende Code:The preceding code:
Ruft UseDeveloperExceptionPage auf, wenn
ASPNETCORE_ENVIRONMENT
aufDevelopment
festgelegt ist.Calls UseDeveloperExceptionPage whenASPNETCORE_ENVIRONMENT
is set toDevelopment
.Ruft UseExceptionHandler auf, wenn der Wert von
ASPNETCORE_ENVIRONMENT
auf einen der folgenden Werte festgelegt ist:Calls UseExceptionHandler when the value ofASPNETCORE_ENVIRONMENT
is set one of the following:Staging
Production
Staging_2
Das Umgebungstaghilfsprogramm verwendet den Wert von IHostingEnvironment.EnvironmentName
zum Einschließen oder Ausschließen von Markup im Element:The Environment Tag Helper uses the value of IHostingEnvironment.EnvironmentName
to include or exclude markup in the element:
<environment include="Development">
<div>The effective tag is: <environment include="Development"></div>
</environment>
<environment exclude="Development">
<div>The effective tag is: <environment exclude="Development"></div>
</environment>
<environment include="Staging,Development,Staging_2">
<div>
The effective tag is:
<environment include="Staging,Development,Staging_2">
</div>
</environment>
Unter Windows und macOS wird bei Umgebungsvariablen und Werten die Groß-/Kleinschreibung nicht beachtet.On Windows and macOS, environment variables and values aren't case-sensitive. Bei Linux-Umgebungsvariablen und -Werten wird die Groß-/Kleinschreibung standardmäßig beachtet.Linux environment variables and values are case-sensitive by default.
EntwicklungDevelopment
In der Entwicklungsumgebung können Features aktiviert werden, die in der Produktion nicht verfügbar gemacht werden sollten.The development environment can enable features that shouldn't be exposed in production. Mit den ASP.NET Core-Vorlagen wird beispielsweise die Seite mit Ausnahmen für Entwickler in der Entwicklungsumgebung aktiviert.For example, the ASP.NET Core templates enable the Developer Exception Page in the development environment.
Die Umgebung für die Entwicklung lokaler Computer kann in der Datei Properties\launchSettings.json des Projekts festgelegt werden.The environment for local machine development can be set in the Properties\launchSettings.json file of the project. Mit in der Datei launchSettings.json festgelegten Umgebungsvariablen werden in der Systemumgebung festgelegte Werte überschrieben.Environment values set in launchSettings.json override values set in the system environment.
Die folgende JSON zeigt drei Profile aus der Datei launchSettings.json an:The following JSON shows three profiles from a launchSettings.json file:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:54339/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_My_Environment": "1",
"ASPNETCORE_DETAILEDERRORS": "1",
"ASPNETCORE_ENVIRONMENT": "Staging"
}
},
"EnvironmentsSample": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Staging"
},
"applicationUrl": "http://localhost:54340/"
},
"Kestrel Staging": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_My_Environment": "1",
"ASPNETCORE_DETAILEDERRORS": "1",
"ASPNETCORE_ENVIRONMENT": "Staging"
},
"applicationUrl": "http://localhost:51997/"
}
}
}
Hinweis
Die Eigenschaft applicationUrl
in launchSettings.json kann eine Liste von Server-URLs angeben.The applicationUrl
property in launchSettings.json can specify a list of server URLs. Verwenden Sie ein Semikolon zwischen den URLs in der Liste:Use a semicolon between the URLs in the list:
"EnvironmentsSample": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
Wenn die Anwendung mit dotnet run gestartet wird, wird das erste Profil mit "commandName": "Project"
verwendet.When the app is launched with dotnet run, the first profile with "commandName": "Project"
is used. Der Wert von commandName
gibt den zu startenden Webserver an.The value of commandName
specifies the web server to launch. commandName
kann einer der folgenden sein:commandName
can be any one of the following:
IISExpress
IIS
Project
(über das Kestrel gestartet wird)Project
(which launches Kestrel)
Beim Start einer App mit dotnet run tritt Folgendes ein:When an app is launched with dotnet run:
- Die Datei launchSettings.json wird, sofern verfügbar, gelesen.launchSettings.json is read if available. Durch
environmentVariables
-Einstellungen in der Datei launchSettings.json werden Umgebungsvariablen überschrieben.environmentVariables
settings in launchSettings.json override environment variables. - Die Hostingumgebung wird angezeigt.The hosting environment is displayed.
Die folgende Ausgabe zeigt eine App, die mit dotnet run gestartet wurde:The following output shows an app started with dotnet run:
PS C:\Websites\EnvironmentsSample> dotnet run
Using launch settings from C:\Websites\EnvironmentsSample\Properties\launchSettings.json...
Hosting environment: Staging
Content root path: C:\Websites\EnvironmentsSample
Now listening on: http://localhost:54340
Application started. Press Ctrl+C to shut down.
Auf der Registerkarte Debuggen der Visual Studio-Projekteigenschaften wird eine grafische Benutzeroberfläche für die Bearbeitung der Datei launchSettings.json bereitgestellt:The Visual Studio project properties Debug tab provides a GUI to edit the launchSettings.json file:
An Projektprofilen vorgenommene Änderungen werden möglicherweise erst nach einem Neustart des Webservers wirksam.Changes made to project profiles may not take effect until the web server is restarted. Kestrel muss neu gestartet werden, bevor es an der Umgebung vorgenommene Änderungen erkennen kann.Kestrel must be restarted before it can detect changes made to its environment.
Warnung
In der Datei launchSettings.json sollten keine geheimen Schlüssel gespeichert werden.launchSettings.json shouldn't store secrets. Mit dem Secret Manager-Tool können geheime Schlüssel für die lokale Umgebung gespeichert werden.The Secret Manager tool can be used to store secrets for local development.
Wenn Sie Visual Studio Code verwenden, können Umgebungsvariablen in der Datei .vscode/launch.json festgelegt werden.When using Visual Studio Code, environment variables can be set in the .vscode/launch.json file. Im folgenden Beispiel wird die Umgebung auf Development
festgelegt:The following example sets the environment to Development
:
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
... additional VS Code configuration settings ...
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
]
}
Die Datei .vscode/launch.json im Projekt wird nicht gelesen, wenn die App mit dotnet run
genauso wie Properties/launchSettings.json gestartet wird.A .vscode/launch.json file in the project isn't read when starting the app with dotnet run
in the same way as Properties/launchSettings.json. Wenn Sie eine App in der Entwicklung starten, die keine launchSettings.json-Datei enthält, legen Sie die Umgebung mit einer Umgebungsvariablen oder einem Befehlszeilenargument auf den dotnet run
-Befehl fest.When launching an app in development that doesn't have a launchSettings.json file, either set the environment with an environment variable or a command-line argument to the dotnet run
command.
ProduktionProduction
Die Produktionsumgebung sollte so konfiguriert werden, dass Sicherheit, Leistung und Stabilität der App maximiert werden.The production environment should be configured to maximize security, performance, and app robustness. Allgemeine Einstellungen, die sich von der Entwicklung unterscheiden, sind zum Beispiel:Some common settings that differ from development include:
- Zwischenspeicherung.Caching.
- Clientseitige Ressourcen werden gebündelt, verkleinert und potenziell von einem CDN bedient.Client-side resources are bundled, minified, and potentially served from a CDN.
- Seiten zur Fehlerdiagnose sind deaktiviert.Diagnostic error pages disabled.
- Angezeigte Fehlerseiten sind aktiviert.Friendly error pages enabled.
- Die Produktionsprotokollierung und -überwachung ist aktiviert.Production logging and monitoring enabled. Beispiel: Application Insights.For example, Application Insights.
Festlegen der UmgebungSet the environment
Häufig ist es sinnvoll, mit einer Umgebungsvariablen oder Plattformeinstellung eine bestimmte Umgebung für Tests festzulegen.It's often useful to set a specific environment for testing with an environment variable or platform setting. Wenn die Umgebung nicht festgelegt ist, wird Production
als Standardwert verwendet, wodurch die meisten Debugfeatures deaktiviert werden.If the environment isn't set, it defaults to Production
, which disables most debugging features. Welche Methode zum Festlegen der Umgebung verwendet wird, hängt vom Betriebssystem ab.The method for setting the environment depends on the operating system.
Wenn der Host erstellt wird, bestimmt die letzte von der App gelesene Umgebungseinstellung die Umgebung der App.When the host is built, the last environment setting read by the app determines the app's environment. Die Umgebung der App kann nicht geändert werden, während die App ausgeführt wird.The app's environment can't be changed while the app is running.
Umgebungsvariable oder PlattformeinstellungEnvironment variable or platform setting
Azure App ServiceAzure App Service
Führen Sie die folgenden Schritte durch, um die Umgebung in Azure App Service festzulegen:To set the environment in Azure App Service, perform the following steps:
- Wählen Sie die App auf dem Blatt App Services aus.Select the app from the App Services blade.
- Wählen Sie in der Gruppe Einstellungen das Blatt Konfiguration aus.In the Settings group, select the Configuration blade.
- Wählen Sie auf der Registerkarte Anwendungseinstellungen Neue Anwendungseinstellung aus.In the Application settings tab, select New application setting.
- Geben Sie im Fenster Anwendungseinstellung hinzufügen/bearbeiten
ASPNETCORE_ENVIRONMENT
als Namen an.In the Add/Edit application setting window, provideASPNETCORE_ENVIRONMENT
for the Name. Geben Sie als Wert die Umgebung ein (beispielsweiseStaging
).For Value, provide the environment (for example,Staging
). - Aktivieren Sie das Kontrollkästchen Bereitstellungssloteinstellung, wenn Sie möchten, dass die Umgebungseinstellung im aktuellen Slot bleibt, wenn Bereitstellungsslots getauscht werden.Select the Deployment slot setting check box if you wish the environment setting to remain with the current slot when deployment slots are swapped. Weitere Informationen finden Sie unter Einrichten von Stagingumgebungen in Azure App Service in der Azure-Dokumentation.For more information, see Set up staging environments in Azure App Service in the Azure documentation.
- Wählen Sie OK aus, um das Fenster Anwendungseinstellung hinzufügen/bearbeiten zu schließen.Select OK to close the Add/Edit application setting window.
- Klicken Sie oben auf dem Blatt Konfiguration auf Speichern.Select Save at the top of the Configuration blade.
Azure App Service startet die App automatisch neu, nachdem eine App-Einstellung (Umgebungsvariable) im Azure-Portal hinzugefügt, geändert oder gelöscht wurde.Azure App Service automatically restarts the app after an app setting (environment variable) is added, changed, or deleted in the Azure portal.
WindowsWindows
Zum Festlegen der ASPNETCORE_ENVIRONMENT
für die aktuelle Sitzung werden folgende Befehle verwendet, wenn die App mit dotnet run gestartet wird:To set the ASPNETCORE_ENVIRONMENT
for the current session when the app is started using dotnet run, the following commands are used:
EingabeaufforderungCommand prompt
set ASPNETCORE_ENVIRONMENT=Development
PowerShellPowerShell
$Env:ASPNETCORE_ENVIRONMENT = "Development"
Diese Befehle sind nur für das aktuelle Fenster wirksam.These commands only take effect for the current window. Wenn das Fenster geschlossen wird, wird die Einstellung ASPNETCORE_ENVIRONMENT
auf die Standardeinstellung oder den Computerwert zurückgesetzt.When the window is closed, the ASPNETCORE_ENVIRONMENT
setting reverts to the default setting or machine value.
Wenn Sie den Wert in Windows global festlegen möchten, nutzen Sie eine der folgenden Möglichkeiten:To set the value globally in Windows, use either of the following approaches:
Öffnen Sie Systemsteuerung > System > Erweiterte Systemeinstellungen, und fügen Sie den Wert
ASPNETCORE_ENVIRONMENT
hinzu, oder bearbeiten Sie ihn:Open the Control Panel > System > Advanced system settings and add or edit theASPNETCORE_ENVIRONMENT
value:Führen Sie die Eingabeaufforderung als Administrator aus, und verwenden Sie den Befehl
setx
. Alternativ können Sie auch die PowerShell-Eingabeaufforderung als Administrator ausführen und[Environment]::SetEnvironmentVariable
nutzen:Open an administrative command prompt and use thesetx
command or open an administrative PowerShell command prompt and use[Environment]::SetEnvironmentVariable
:EingabeaufforderungCommand prompt
setx ASPNETCORE_ENVIRONMENT Development /M
Mit dem Parameter
/M
wird angegeben, dass die Umgebungsvariable auf Systemebene festgelegt wird.The/M
switch indicates to set the environment variable at the system level. Ohne den Parameter/M
wird die Umgebungsvariable für das Nutzerkonto festgelegt.If the/M
switch isn't used, the environment variable is set for the user account.PowerShellPowerShell
[Environment]::SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development", "Machine")
Mit dem Optionswert
Machine
wird angegeben, dass die Umgebungsvariable auf Systemebene festgelegt wird.TheMachine
option value indicates to set the environment variable at the system level. Verwenden Sie stattdessen den OptionswertUser
, wird die Umgebungsvariable für das Nutzerkonto festgelegt.If the option value is changed toUser
, the environment variable is set for the user account.
Sobald die Umgebungsvariable ASPNETCORE_ENVIRONMENT
global festgelegt wird, gilt sie in jedem geöffneten Befehlsfenster für dotnet run
.When the ASPNETCORE_ENVIRONMENT
environment variable is set globally, it takes effect for dotnet run
in any command window opened after the value is set.
web.configweb.config
Eine Anleitung zum Festlegen der Umgebungsvariable ASPNETCORE_ENVIRONMENT
mit web.config finden Sie im Abschnitt Festlegen von Umgebungsvariablen der im Artikel zu ASP.NET Core-Modul.To set the ASPNETCORE_ENVIRONMENT
environment variable with web.config, see the Setting environment variables section of ASP.NET Core-Modul.
Projektdatei oder VeröffentlichungsprofilProject file or publish profile
Für Windows IIS-Bereitstellungen: Beziehen Sie die <EnvironmentName>
-Eigenschaft in das Veröffentlichungsprofil (PUBXML) oder die Projektdatei ein.For Windows IIS deployments: Include the <EnvironmentName>
property in the publish profile (.pubxml) or project file. Dieser Ansatz legt die Umgebung in web.config fest, wenn das Projekt veröffentlicht wird:This approach sets the environment in web.config when the project is published:
<PropertyGroup>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
Pro IIS-AnwendungspoolPer IIS Application Pool
Wenn Sie für eine App, die in einem isolierten Anwendungspool ausgeführt wird, die Umgebungsvariable ASPNETCORE_ENVIRONMENT
festlegen möchten (unterstützt in IIS 10.0 oder höher), lesen Sie den Abschnitt AppCmd.exe command (Befehl „AppCmd.exe“) im Artikel zu Umgebungsvariablen<environmentVariables>.To set the ASPNETCORE_ENVIRONMENT
environment variable for an app running in an isolated Application Pool (supported on IIS 10.0 or later), see the AppCmd.exe command section of the Environment Variables <environmentVariables> topic. Wurde die Umgebungsvariable ASPNETCORE_ENVIRONMENT
für einen Anwendungspool festgelegt, überschreibt der Wert die Einstellung auf Systemebene.When the ASPNETCORE_ENVIRONMENT
environment variable is set for an app pool, its value overrides a setting at the system level.
Wichtig
Wenn Sie eine APP in den IIS hosten und die Umgebungsvariable ASPNETCORE_ENVIRONMENT
hinzufügen oder ändern, sorgen Sie auf eine der folgenden Arten und Weisen dafür, dass der neue Wert in den Apps hinterlegt ist:When hosting an app in IIS and adding or changing the ASPNETCORE_ENVIRONMENT
environment variable, use any one of the following approaches to have the new value picked up by apps:
- Führen Sie in einer Eingabeaufforderung
net stop was /y
gefolgt vonnet start w3svc
aus.Executenet stop was /y
followed bynet start w3svc
from a command prompt. - Starten Sie den Server neu.Restart the server.
macOSmacOS
Das Festlegen der aktuellen Umgebung für macOS kann inline während der Ausführung der App erfolgen:Setting the current environment for macOS can be performed in-line when running the app:
ASPNETCORE_ENVIRONMENT=Development dotnet run
Legen Sie die Umgebung alternativ mit export
vor der Ausführung der App fest:Alternatively, set the environment with export
prior to running the app:
export ASPNETCORE_ENVIRONMENT=Development
Umgebungsvariablen auf Computerebene werden in der BASHRC- oder BASH_PROFILE-Datei festgelegt.Machine-level environment variables are set in the .bashrc or .bash_profile file. Bearbeiten Sie die Datei mit einem beliebigen Text-Editor.Edit the file using any text editor. Fügen Sie die folgende Anweisung hinzu:Add the following statement:
export ASPNETCORE_ENVIRONMENT=Development
LinuxLinux
Verwenden Sie bei Linux-Distributionen für sitzungsbasierte Variableneinstellungen den Befehl export
in der Eingabeaufforderung und die Datei bash_profile für Umgebungseinstellungen auf Computerebene.For Linux distributions, use the export
command at a command prompt for session-based variable settings and bash_profile file for machine-level environment settings.
Festlegen der Umgebung im CodeSet the environment in code
Rufen Sie beim Erstellen des Hosts UseEnvironment auf.Call UseEnvironment when building the host. Siehe ASP.NET Core-Webhost.See ASP.NET Core-Webhost.
Konfiguration nach UmgebungConfiguration by environment
Zum Laden von „Konfiguration nach Umgebung“ empfehlen wir:To load configuration by environment, we recommend:
- appsettings-Dateien (appsettings.{Umgebung}.json).appsettings files (appsettings.{Environment}.json). Siehe Konfiguration in ASP.NET Core.See Konfiguration in ASP.NET Core.
- Umgebungsvariablen (in jedem System festgelegt, in dem die App gehostet wird).Environment variables (set on each system where the app is hosted). Weitere Informationen finden Sie unter ASP.NET Core-Webhost und Sichere Speicherung von App-Geheimnissen in der Entwicklung in ASP.net Core.See ASP.NET Core-Webhost and Sichere Speicherung von App-Geheimnissen in der Entwicklung in ASP.net Core.
- Secret Manager (nur in der Entwicklungsumgebung)Secret Manager (in the Development environment only). Siehe Sichere Speicherung von App-Geheimnissen in der Entwicklung in ASP.net Core.See Sichere Speicherung von App-Geheimnissen in der Entwicklung in ASP.net Core.
Umgebungsbasierte Startklasse und MethodenEnvironment-based Startup class and methods
Einfügen von IHostingEnvironment in Startup.ConfigureInject IHostingEnvironment into Startup.Configure
Fügen Sie IHostingEnvironment in Startup.Configure
ein.Inject IHostingEnvironment into Startup.Configure
. Diese Vorgehensweise ist nützlich, wenn die App Startup.Configure
nur für einige Umgebungen mit minimalen Codeunterschieden pro Umgebung konfigurieren muss.This approach is useful when the app only requires configuring Startup.Configure
for only a few environments with minimal code differences per environment.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
// Development environment code
}
else
{
// Code for all other environments
}
}
Einfügen von IHostingEnvironment in die StartklasseInject IHostingEnvironment into the Startup class
Fügen Sie IHostingEnvironment in den Startup
-Konstruktor ein, und weisen Sie den Dienst einem Feld zu, das in der gesamten Startup
-Klasse verwendet werden soll.Inject IHostingEnvironment into the Startup
constructor and assign the service to a field for use throughout the Startup
class. Diese Vorgehensweise ist nützlich, wenn die App „Startup“ nur für einige Umgebungen mit minimalen Codeunterschieden pro Umgebung konfigurieren muss.This approach is useful when the app requires configuring startup for only a few environments with minimal code differences per environment.
Im folgenden Beispiel:In the following example:
- Die Umgebung wird im Feld
_env
gespeichert.The environment is held in the_env
field. _env
wird inConfigureServices
undConfigure
verwendet, um die Startkonfiguration basierend auf der Umgebung der App anzuwenden._env
is used inConfigureServices
andConfigure
to apply startup configuration based on the app's environment.
public class Startup
{
private readonly IHostingEnvironment _env;
public Startup(IHostingEnvironment env)
{
_env = env;
}
public void ConfigureServices(IServiceCollection services)
{
if (_env.IsDevelopment())
{
// Development environment code
}
else if (_env.IsStaging())
{
// Staging environment code
}
else
{
// Code for all other environments
}
}
public void Configure(IApplicationBuilder app)
{
if (_env.IsDevelopment())
{
// Development environment code
}
else
{
// Code for all other environments
}
}
}
Konventionen der Startup-KlasseStartup class conventions
Nach dem Start einer ASP.NET Core-App lädt die Startklasse die App.When an ASP.NET Core app starts, the Startup class bootstraps the app. Die App kann je nach Umgebung unterschiedliche Startup
-Klassen definieren (z. B. StartupDevelopment
).The app can define separate Startup
classes for different environments (for example, StartupDevelopment
). Die entsprechende Startup
-Klasse wird zur Laufzeit ausgewählt.The appropriate Startup
class is selected at runtime. Die Klasse, deren Namenssuffix mit der aktuellen Umgebung übereinstimmt, wird priorisiert.The class whose name suffix matches the current environment is prioritized. Ist keine übereinstimmende Startup{EnvironmentName}
-Klasse vorhanden, wird die Klasse Startup
verwendet.If a matching Startup{EnvironmentName}
class isn't found, the Startup
class is used. Diese Vorgehensweise ist nützlich, wenn die App „Startup“ für mehrere Umgebungen mit vielen Codeunterschieden pro Umgebung konfigurieren muss.This approach is useful when the app requires configuring startup for several environments with many code differences per environment.
Wenn Sie umgebungsbasierte Startup
-Klassen implementieren möchten, erstellen Sie für jedes verwendete Element eine Startup{EnvironmentName}
-Klasse und eine Fallback-Klasse des Typs Startup
:To implement environment-based Startup
classes, create a Startup{EnvironmentName}
class for each environment in use and a fallback Startup
class:
// Startup class to use in the Development environment
public class StartupDevelopment
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
}
}
// Startup class to use in the Production environment
public class StartupProduction
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
}
}
// Fallback Startup class
// Selected if the environment doesn't match a Startup{EnvironmentName} class
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
}
}
Verwenden Sie die Überladung UseStartup(IWebHostBuilder, String), die einen Assemblynamen akzeptiert:Use the UseStartup(IWebHostBuilder, String) overload that accepts an assembly name:
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var assemblyName = typeof(Startup).GetTypeInfo().Assembly.FullName;
return WebHost.CreateDefaultBuilder(args)
.UseStartup(assemblyName);
}
Konventionen der Methode „Start“Startup method conventions
Configure und ConfigureServices unterstützen umgebungsspezifische Versionen der Form Configure<EnvironmentName>
und Configure<EnvironmentName>Services
.Configure and ConfigureServices support environment-specific versions of the form Configure<EnvironmentName>
and Configure<EnvironmentName>Services
. Diese Vorgehensweise ist nützlich, wenn die App „Startup“ für mehrere Umgebungen mit vielen Codeunterschieden pro Umgebung konfigurieren muss.This approach is useful when the app requires configuring startup for several environments with many code differences per environment.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
StartupConfigureServices(services);
}
public void ConfigureStagingServices(IServiceCollection services)
{
StartupConfigureServices(services);
}
private void StartupConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
if (env.IsProduction() || env.IsStaging() || env.IsEnvironment("Staging_2"))
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseMvc();
}
public void ConfigureStaging(IApplicationBuilder app, IHostingEnvironment env)
{
if (!env.IsStaging())
{
throw new Exception("Not staging.");
}
app.UseExceptionHandler("/Error");
app.UseStaticFiles();
app.UseMvc();
}
}