在 ASP.NET Core 中使用多個環境Use multiple environments in ASP.NET Core

作者:Rick AndersonBy Rick Anderson

ASP.NET Core 會使用環境變數根據執行階段環境來設定應用程式行為。ASP.NET Core configures app behavior based on the runtime environment using an environment variable.

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

環境Environments

ASP.NET Core 會在應用程式啟動時讀取 ASPNETCORE_ENVIRONMENT 環境變數,並將該值儲存在 IHostingEnvironment.EnvironmentName 中。ASP.NET Core reads the environment variable ASPNETCORE_ENVIRONMENT at app startup and stores the value in IHostingEnvironment.EnvironmentName. 您可將 ASPNETCORE_ENVIRONMENT 設定為任何值,但架構支援下列三個值DevelopmentStagingProductionYou can set ASPNETCORE_ENVIRONMENT to any value, but three values are supported by the framework: Development, Staging, and Production. 如果未設定 ASPNETCORE_ENVIRONMENT,則預設為 ProductionIf ASPNETCORE_ENVIRONMENT isn't set, it defaults to Production.

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();
}

上述程式碼:The preceding code:

環境標籤協助程式會使用 IHostingEnvironment.EnvironmentName 的值來包含或排除項目中的標籤:The Environment Tag Helper uses the value of IHostingEnvironment.EnvironmentName to include or exclude markup in the element:

<environment include="Development">
    <div>&lt;environment include="Development"&gt;</div>
</environment>
<environment exclude="Development">
    <div>&lt;environment exclude="Development"&gt;</div>
</environment>
<environment include="Staging,Development,Staging_2">
    <div>
        &lt;environment include="Staging,Development,Staging_2"&gt;
    </div>
</environment>

在 Windows 及 macOS 中,環境變數和值不區分大小寫。On Windows and macOS, environment variables and values aren't case sensitive. Linux 的環境變數和值則預設為區分大小寫Linux environment variables and values are case sensitive by default.

開發Development

您可以在開發環境中啟用生產環境不應該公開的功能。The development environment can enable features that shouldn't be exposed in production. 例如,ASP.NET Core 範本會在開發環境中啟用開發人員例外狀況頁面For example, the ASP.NET Core templates enable the Developer Exception Page in the development environment.

您可以在專案的 Properties\launchSettings.json 檔案設定適用於本機電腦開發的環境。The environment for local machine development can be set in the Properties\launchSettings.json file of the project. launchSettings.json 中設定的環境值會覆寫系統環境的設定值。Environment values set in launchSettings.json override values set in the system environment.

下列 JSON 顯示來自 launchSettings.json 檔案的三個設定檔: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/"
    }
  }
}

注意

launchSettings.json 中的 applicationUrl 屬性可以指定伺服器 URL 的清單。The applicationUrl property in launchSettings.json can specify a list of server URLs. 請在清單的 URL 之間使用分號: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"
   }
}

dotnet run 啟動應用程式時,會使用具有 "commandName": "Project" 的第一個設定檔。When the app is launched with dotnet run, the first profile with "commandName": "Project" is used. commandName 的值可指定要啟動的網頁伺服器。The value of commandName specifies the web server to launch. commandName 可以是下列任何一個項目:commandName can be any one of the following:

  • IISExpress
  • IIS
  • Project (這會啟動 Kestrel)Project (which launches Kestrel)

dotnet run 啟動應用程式時:When an app is launched with dotnet run:

  • 會讀取 launchSettings.json (如果有的話)。launchSettings.json is read if available. launchSettings.json 中的 environmentVariables 設定會覆寫環境變數。environmentVariables settings in launchSettings.json override environment variables.
  • 主控環境隨即顯示。The hosting environment is displayed.

下列輸出顯示應用程式是以 dotnet run 啟動: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.

Visual Studio 專案屬性的 [偵錯] 索引標籤提供 GUI,可編輯 launchSettings.json 檔案:The Visual Studio project properties Debug tab provides a GUI to edit the launchSettings.json file:

專案屬性設定環境變數

您對專案設定檔所做的變更可能要等重新啟動網頁伺服器後才會生效。Changes made to project profiles may not take effect until the web server is restarted. 您必須重新啟動 Kestrel,它才會偵測到環境已進行的變更。Kestrel must be restarted before it can detect changes made to its environment.

警告

launchSettings.json 不應儲存密碼。launchSettings.json shouldn't store secrets. 密碼管理員工具可以用來儲存本機開發的密碼。The Secret Manager tool can be used to store secrets for local development.

使用 Visual Studio Code 時,可以會在 .vscode/launch.json 檔案設定環境變數。When using Visual Studio Code, environment variables can be set in the .vscode/launch.json file. 下列範例會將環境設定為 DevelopmentThe 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"
            }
        }
    ]
}

使用 dotnet run 啟動應用程式時,不會如同 Properties/launchSettings.json 一樣讀取專案中的 .vscode/launch.json 檔。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. 開發時若啟動的應用程式沒有 launchSettings.json 檔,請使用環境變數設定環境,或是使用 dotnet run 命令的命令列引數。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.

生產環境Production

若要將安全性、效能及應用程式加強性最大化,您應該設定生產環境。The production environment should be configured to maximize security, performance, and app robustness. 不同於開發的某些一般設定包括:Some common settings that differ from development include:

  • 快取。Caching.
  • 用戶端的資源會經過配套、縮減,且可能由 CDN 提供。Client-side resources are bundled, minified, and potentially served from a CDN.
  • 停用診斷錯誤頁面。Diagnostic error pages disabled.
  • 啟用易懂的錯誤頁面。Friendly error pages enabled.
  • 啟用生產記錄與監視。Production logging and monitoring enabled. 例如 Application InsightsFor example, Application Insights.

設定環境Set the environment

一般來說,設定特定環境以進行測試,是很實用的方法。It's often useful to set a specific environment for testing. 如果您未設定環境,它會預設為 Production 並停用大部分的偵錯功能。If the environment isn't set, it defaults to Production, which disables most debugging features. 環境的設定方法取決於作業系統而定。The method for setting the environment depends on the operating system.

Azure App ServiceAzure App Service

若要在 Azure App Service 設定環境,請執行下列步驟:To set the environment in Azure App Service, perform the following steps:

  1. 從 [應用程式服務] 刀鋒視窗選取應用程式。Select the app from the App Services blade.
  2. 在 [設定] 群組中,選取 [應用程式設定] 刀鋒視窗。In the SETTINGS group, select the Application settings blade.
  3. 在 [應用程式設定] 區域中,選取 [新增設定]。In the Application settings area, select Add new setting.
  4. 針對 [輸入名稱],提供 ASPNETCORE_ENVIRONMENTFor Enter a name, provide ASPNETCORE_ENVIRONMENT. 針對 [輸入值],提供環境 (例如 Staging)。For Enter a value, provide the environment (for example, Staging).
  5. 如果您想要在交換部署位置時,環境設定保留目前的位置,請選取 [位置設定] 核取方塊。Select the Slot Setting check box if you wish the environment setting to remain with the current slot when deployment slots are swapped. 如需詳細資訊,請參閱 Azure 文件:哪些設定已交換For more information, see Azure Documentation: Which settings are swapped?.
  6. 選取刀鋒視窗頂端的 [儲存]。Select Save at the top of the blade.

Azure App Service 會在新增、變更或刪除 Azure 入口網站的應用程式設定 (環境變數) 之後自動重新啟動應用程式。Azure App Service automatically restarts the app after an app setting (environment variable) is added, changed, or deleted in the Azure portal.

WindowsWindows

如果應用程式是使用 dotnet run 啟動,請使用下列命令來設定目前工作階段的 ASPNETCORE_ENVIRONMENTTo set the ASPNETCORE_ENVIRONMENT for the current session when the app is started using dotnet run, the following commands are used:

命令提示字元Command prompt

set ASPNETCORE_ENVIRONMENT=Development

PowerShellPowerShell

$Env:ASPNETCORE_ENVIRONMENT = "Development"

這些命令僅針對目前的視窗才會生效。These commands only take effect for the current window. 視窗關閉時,ASPNETCORE_ENVIRONMENT 設定會還原為預設值或電腦值。When the window is closed, the ASPNETCORE_ENVIRONMENT setting reverts to the default setting or machine value.

若要在 Windows 中以全域的方式設定值,請使用下列其中一個方法:To set the value globally in Windows, use either of the following approaches:

  • 開啟 [控制台] > [系統] > [進階系統設定],然後新增或編輯 ASPNETCORE_ENVIRONMENT 值:Open the Control Panel > System > Advanced system settings and add or edit the ASPNETCORE_ENVIRONMENT value:

    系統進階屬性

    ASPNET Core 環境變數

  • 開啟系統管理命令提示字元,然後使用 setx 命令,或開啟系統管理 PowerShell 命令提示字元,然後使用 [Environment]::SetEnvironmentVariableOpen an administrative command prompt and use the setx command or open an administrative PowerShell command prompt and use [Environment]::SetEnvironmentVariable:

    命令提示字元Command prompt

    setx ASPNETCORE_ENVIRONMENT Development /M
    

    /M 參數表示將環境變數設定在系統層級。The /M switch indicates to set the environment variable at the system level. 若未使用 /M 參數,則將環境變數設定為使用者帳戶。If the /M switch isn't used, the environment variable is set for the user account.

    PowerShellPowerShell

    [Environment]::SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development", "Machine")
    

    Machine 選項值表示將環境變數設定在系統層級。The Machine option value indicates to set the environment variable at the system level. 若選項值變更為 User,則將環境變數設定為使用者帳戶。If the option value is changed to User, the environment variable is set for the user account.

當以全域的方式設定 ASPNETCORE_ENVIRONMENT 環境變數時,則在設定該值後開啟的任何命令視窗中,對 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

若要使用 web.config 設定 ASPNETCORE_ENVIRONMENT 環境變數,請參閱 ASP.NET Core 模組 的<設定環境變數>一節。To set the ASPNETCORE_ENVIRONMENT environment variable with web.config, see the Setting environment variables section of ASP.NET Core 模組.

專案檔或發行設定檔Project file or publish profile

適用於 Windows IIS 部署: 在發行設定檔 (.pubxml) 或專案檔中包括 <EnvironmentName> 屬性。For Windows IIS deployments: Include the <EnvironmentName> property in the publish profile (.pubxml) or project file. 此方法會在專案發行時於 web.config 中設定環境:This approach sets the environment in web.config when the project is published:

<PropertyGroup>
  <EnvironmentName>Development</EnvironmentName>
</PropertyGroup>

每個 IIS 應用程式集區Per IIS Application Pool

若要為執行於隔離應用程式集區 (受 IIS 10.0 或更新版本支援) 的應用程式設定 ASPNETCORE_ENVIRONMENT 環境變數,請參閱環境變數 <environmentVariables> 主題的<AppCmd.exe 命令>一節。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. ASPNETCORE_ENVIRONMENT 環境變數設定為應用程式集區時,其值會覆寫系統層級的設定。When the ASPNETCORE_ENVIRONMENT environment variable is set for an app pool, its value overrides a setting at the system level.

重要

當在 IIS 中裝載應用程式,並新增或變更 ASPNETCORE_ENVIRONMENT 環境變數時,請使用下列任一種方法,讓應用程式挑選新的值: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:

  • 從命令提示字元執行後面接著 net start w3svcnet stop was /yExecute net stop was /y followed by net start w3svc from a command prompt.
  • 重新啟動伺服器。Restart the server.

macOSmacOS

您可以在執行應用程式時,以內嵌方式設定 macOS 目前的環境:Setting the current environment for macOS can be performed in-line when running the app:

ASPNETCORE_ENVIRONMENT=Development dotnet run

或者,在執行應用程式之前,使用 export 設定環境:Alternatively, set the environment with export prior to running the app:

export ASPNETCORE_ENVIRONMENT=Development

您可以在 .bashrc.bash_profile 檔案中設定電腦層級的環境變數。Machine-level environment variables are set in the .bashrc or .bash_profile file. 使用任何文字編輯器編輯檔案。Edit the file using any text editor. 新增下列陳述式:Add the following statement:

export ASPNETCORE_ENVIRONMENT=Development

LinuxLinux

針對 Linux 散發版本,請在命令提示字元使用 export 命令,進行以工作階段為基礎的變數設定,並使用 bash_profile 檔案,進行電腦層級的環境設定。For Linux distros, use the export command at a command prompt for session-based variable settings and bash_profile file for machine-level environment settings.

取決於環境的組態Configuration by environment

若要依環境載入組態,建議使用:To load configuration by environment, we recommend:

以環境為基礎的 Startup 類別和方法Environment-based Startup class and methods

Startup 類別慣例Startup class conventions

ASP.NET Core 應用程式啟動時,Startup 類別會啟動應用程式。When an ASP.NET Core app starts, the Startup class bootstraps the app. 應用程式可以針對不同的環境定義個別的 Startup 類別 (例如 StartupDevelopment),並在執行階段選取適當的 Startup 類別。The app can define separate Startup classes for different environments (for example, StartupDevelopment), and the appropriate Startup class is selected at runtime. 將優先使用其名稱尾碼符合目前環境的類別。The class whose name suffix matches the current environment is prioritized. 如果找不到相符的 Startup{EnvironmentName} 類別,會使用 Startup 類別。If a matching Startup{EnvironmentName} class isn't found, the Startup class is used.

若要實作以環境為基礎的 Startup 類別,請為每個使用中的環境建立 Startup{EnvironmentName} 類別和後援 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)
    {
        ...
    }
}

使用接受組件名稱的 UseStartup(IWebHostBuilder, String) 多載: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);
}

Startup 方法慣例Startup method conventions

ConfigureConfigureServices 支援表單 Configure<EnvironmentName>Configure<EnvironmentName>Services 的環境特定版本:Configure and ConfigureServices support environment-specific versions of the form Configure<EnvironmentName> and Configure<EnvironmentName>Services:

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();
    }
}

其他資源Additional resources