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

Rick AndersonKirk LarkinBy Rick Anderson and Kirk Larkin

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 從下列環境變數讀取:To determine the runtime environment, ASP.NET Core reads from the following environment variables:

  1. DOTNET_ENVIRONMENTDOTNET_ENVIRONMENT
  2. ASPNETCORE_ENVIRONMENTConfigureWebHostDefaults 呼叫時。ASPNETCORE_ENVIRONMENT when ConfigureWebHostDefaults is called. 預設 ASP.NET Core web 應用程式範本呼叫 ConfigureWebHostDefaultsThe default ASP.NET Core web app templates call ConfigureWebHostDefaults. ASPNETCORE_ENVIRONMENT值會覆寫 DOTNET_ENVIRONMENTThe ASPNETCORE_ENVIRONMENT value overrides DOTNET_ENVIRONMENT.

IHostEnvironment.EnvironmentName可以設定為任何值,但下列值是由架構所提供:IHostEnvironment.EnvironmentName can be set to any value, but the following values are provided by the framework:

下列程式碼:The following code:

  • ASPNETCORE_ENVIRONMENT 設為 Development 時,會呼叫 UseDeveloperExceptionPageCalls UseDeveloperExceptionPage when ASPNETCORE_ENVIRONMENT is set to Development.
  • UseExceptionHandler的值 ASPNETCORE_ENVIRONMENT 設定為、或時,會呼叫 UseExceptionHandler Staging Production Staging_2Calls UseExceptionHandler when the value of ASPNETCORE_ENVIRONMENT is set to Staging, Production, or Staging_2.
  • 將插入 IWebHostEnvironmentStartup.ConfigureInjects IWebHostEnvironment into Startup.Configure. 當應用程式只需要調整 Startup.Configure 少數環境,且每個環境的程式碼差異最低時,這個方法就很有用。This approach is useful when the app only requires adjusting Startup.Configure for a few environments with minimal code differences per environment.
  • 類似于 ASP.NET Core 範本所產生的程式碼。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();
    });
}

環境標記協助程式會使用IHostEnvironment的值來包含或排除元素中的標記: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: &lt;environment include="Development"&gt;</div>
</environment>
<environment exclude="Development">
    <div>The effective tag is: &lt;environment exclude="Development"&gt;</div>
</environment>
<environment include="Staging,Development,Staging_2">
    <div>
        The effective tag is:
        &lt;environment include="Staging,Development,Staging_2"&gt;
    </div>
</environment>

範例程式碼中的 [關於] 頁面包含前述標記,並顯示的值 IWebHostEnvironment.EnvironmentNameThe About page from the sample code includes the preceding markup and displays the value of IWebHostEnvironment.EnvironmentName.

在 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.

建立 EnvironmentsSampleCreate EnvironmentsSample

本檔中使用的範例程式碼是以 Razor 名為EnvironmentsSample的頁面專案為基礎。The sample code used in this document is based on a Razor Pages project named EnvironmentsSample.

下列程式碼會建立並執行名為EnvironmentsSample的 web 應用程式:The following code creates and runs a web app named EnvironmentsSample:

dotnet new webapp -o EnvironmentsSample
cd EnvironmentsSample
dotnet run --verbosity normal

當應用程式執行時,它會顯示下列部分輸出: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

開發與 launchSettings.jsDevelopment and launchSettings.json

您可以在開發環境中啟用生產環境不應該公開的功能。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.

檔案上的launchSettings.jsThe launchSettings.json file:

  • 僅用於本機開發電腦。Is only used on the local development machine.
  • 未部署。Is not deployed.
  • 包含設定檔設定。contains profile settings.

下列 JSON 會針對以 Visual Studio 或建立的 ASP.NET Core 網路計畫,顯示名為EnvironmentsSample的檔案launchSettings.js檔案 dotnet newThe 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"
      }
    }
  }
}

上述標記包含兩個設定檔:The preceding markup contains two profiles:

  • IIS Express:從 Visual Studio 啟動應用程式時所使用的預設設定檔。IIS Express: The default profile used when launching the app from Visual Studio. 此索引 "commandName" 鍵的值 "IISExpress" 為,因此, IISExpress是 web 伺服器。The "commandName" key has the value "IISExpress", therefore, IISExpress is the web server. 您可以將啟動設定檔設定為專案或包含的任何其他設定檔。You can set the launch profile to the project or any other profile included. 例如,在下圖中,選取專案名稱會啟動Kestrel web 伺服器For example, in the image below, selecting the project name launches the Kestrel web server.

    IIS Express 在功能表上啟動

  • EnvironmentsSample:設定檔名稱是專案名稱。EnvironmentsSample: The profile name is the project name. 當使用啟動應用程式時,預設會使用此設定檔 dotnet runThis profile is used by default when launching the app with dotnet run. "commandName"金鑰具有值 "Project" ,因此會啟動Kestrel web 伺服器The "commandName" key has the value "Project", therefore, the Kestrel web server is launched.

的值 commandName 可指定要啟動的 web 伺服器。The value of commandName can specify the web server to launch. commandName 可以是下列任何一個項目:commandName can be any one of the following:

  • IISExpress:啟動 IIS Express。IISExpress : Launches IIS Express.
  • IIS:未啟動任何 web 伺服器。IIS : No web server launched. IIS 應該可以使用。IIS is expected to be available.
  • Project:啟動 Kestrel。Project : Launches Kestrel.

[Visual Studio 專案屬性] [調試] 索引標籤會提供 GUI 來編輯檔案上的launchSettings.jsThe 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.js檔案包含多個設定檔: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"
      }
    }
  }
}

可以選取設定檔:Profiles can be selected:

  • 從 [Visual Studio] UI。From the Visual Studio UI.

  • dotnet run在命令 shell 中使用命令,並將 --launch-profile 選項設定為設定檔的名稱。Using the dotnet run command in a command shell with the --launch-profile option set to the profile's name. 這個方法只支援 Kestrel 設定檔。This approach only supports Kestrel profiles.

    dotnet run --launch-profile "SampleApp"
    

警告

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. 下列範例會設定數個主機配置值環境變數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.

檔案的vscode/launch.js僅供 Visual Studio Code 使用。The .vscode/launch.json file is only used by Visual Studio Code.

生產Production

應設定生產環境,以最大化安全性、效能和應用程式的穩定性。The production environment should be configured to maximize security, performance, and application 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, using Application Insights.

設定環境Set the environment

設定特定環境以使用環境變數或平臺設定進行測試時,通常會很有用。It's often useful to set a specific environment for testing with an environment variable or platform setting. 如果您未設定環境,它會預設為 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.

建立主機時,應用程式所讀取的最後一個環境設定會決定應用程式的環境。When the host is built, the last environment setting read by the app determines the app's environment. 應用程式正在執行時,無法變更應用程式的環境。The app's environment can't be changed while the app is running.

範例程式碼中的 [關於] 頁面會顯示的值 IWebHostEnvironment.EnvironmentNameThe About page from the sample code displays the value of IWebHostEnvironment.EnvironmentName.

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 Configuration blade.
  3. 在 [應用程式設定] 索引標籤中,選取 [新增應用程式設定]。In the Application settings tab, select New application setting.
  4. 在 [新增/編輯應用程式設定] 視窗中,提供 ASPNETCORE_ENVIRONMENT 名稱的。In the Add/Edit application setting window, provide ASPNETCORE_ENVIRONMENT for the Name. 針對 [],提供環境(例如 Staging )。For Value, provide the environment (for example, Staging).
  5. 如果您想要在交換部署位置時,將環境設定維持在目前的位置,請選取 [部署位置設定] 核取方塊。Select the Deployment slot setting check box if you wish the environment setting to remain with the current slot when deployment slots are swapped. 如需詳細資訊,請參閱 Azure 檔中的在 Azure App Service 中設定預備環境For more information, see Set up staging environments in Azure App Service in the Azure documentation.
  6. 選取 [確定] 以關閉 [新增/編輯應用程式設定] 視窗。Select OK to close the Add/Edit application setting window.
  7. 選取 [設定] 分頁頂端的 [ 儲存]。Select Save at the top of the Configuration blade.

Azure App Service 在 Azure 入口網站中新增、變更或刪除應用程式設定後,自動重新開機應用程式。Azure App Service automatically restarts the app after an app setting is added, changed, or deleted in the Azure portal.

WindowsWindows

launchSettings.js中的環境值會覆寫系統內容中所設定的覆寫值。Environment values in launchSettings.json override values set in the system environment.

如果應用程式是使用 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=Staging
dotnet run --no-launch-profile

PowerShellPowerShell

$Env:ASPNETCORE_ENVIRONMENT = "Staging"
dotnet run --no-launch-profile

上述命令 ASPNETCORE_ENVIRONMENT 只會設定從該命令視窗啟動的進程。The preceding command sets ASPNETCORE_ENVIRONMENT only for processes launched from that command window.

若要在 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 Staging /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", "Staging", "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. launchSettings.js中的環境值會覆寫系統內容中所設定的覆寫值。Environment values in launchSettings.json override values set in the system environment.

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 部署:<EnvironmentName>將屬性包含在發行設定檔(. .pubxml)或專案檔中。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=Staging dotnet run

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

export ASPNETCORE_ENVIRONMENT=Staging

您可以在 .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=Staging

LinuxLinux

針對 Linux 散發套件,請 export 在命令提示字元中使用命令來進行會話型變數設定,並針對電腦層級的環境設定bash_profile檔案。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.

在程式碼中設定環境Set the environment in code

UseEnvironment在建立主機時呼叫。Call UseEnvironment when building the host. 請參閱< .NET 泛型主機 >。See .NET 泛型主機.

取決於環境的組態Configuration by environment

若要依環境載入設定,請參閱 ASP.NET Core 的設定To load configuration by environment, see ASP.NET Core 的設定.

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

將 IWebHostEnvironment 插入 Startup 類別Inject IWebHostEnvironment into the Startup class

插入 IWebHostEnvironment 至此函式 StartupInject IWebHostEnvironment into the Startup constructor. 當應用程式 Startup 只需要針對少數環境進行設定,而且每個環境的程式碼差異最低時,這個方法就很有用。This approach is useful when the app requires configuring Startup for only a few environments with minimal code differences per environment.

在下例中︰In the following example:

  • 環境會保留在欄位中 _envThe environment is held in the _env field.
  • _env會在和中使用 ConfigureServicesConfigure 以根據應用程式的環境來套用啟動設定。_env is used in ConfigureServices and Configure 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();
        });
    }
}

Startup 類別慣例Startup class conventions

ASP.NET Core 應用程式啟動時,Startup 類別會啟動應用程式。When an ASP.NET Core app starts, the Startup class bootstraps the app. 應用程式可以 Startup 針對不同的環境定義多個類別。The app can define multiple Startup classes for different environments. Startup 執行時間選取適當的類別。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. 當應用程式需要針對數個環境設定啟動,且每個環境有許多程式碼差異時,此方法很有用。This approach is useful when the app requires configuring startup for several environments with many code differences per environment. 一般的應用程式不需要這種方法。Typical apps will not need this approach.

若要執行以環境為基礎的 Startup 類別,請建立 Startup{EnvironmentName} 類別和 fallback 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();
        });
    }
}

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

Startup 方法慣例Startup method conventions

ConfigureConfigureServices支援表單和的環境特定版本 Configure<EnvironmentName> Configure<EnvironmentName>ServicesConfigure and ConfigureServices support environment-specific versions of the form Configure<EnvironmentName> and Configure<EnvironmentName>Services. 當應用程式需要針對數個環境設定啟動,且每個環境有許多程式碼差異時,這個方法會很有用: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}");
    }
}

其他資源Additional resources

作者: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可以設定為任何值,但架構會提供三個值:ASPNETCORE_ENVIRONMENT can be set to any value, but three values are provided by the framework:

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>The effective tag is: &lt;environment include="Development"&gt;</div>
</environment>
<environment exclude="Development">
    <div>The effective tag is: &lt;environment exclude="Development"&gt;</div>
</environment>
<environment include="Staging,Development,Staging_2">
    <div>
        The effective tag is:
        &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 with an environment variable or platform setting. 如果您未設定環境,它會預設為 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.

建立主機時,應用程式所讀取的最後一個環境設定會決定應用程式的環境。When the host is built, the last environment setting read by the app determines the app's environment. 應用程式正在執行時,無法變更應用程式的環境。The app's environment can't be changed while the app is running.

環境變數或平臺設定Environment variable or platform setting

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 Configuration blade.
  3. 在 [應用程式設定] 索引標籤中,選取 [新增應用程式設定]。In the Application settings tab, select New application setting.
  4. 在 [新增/編輯應用程式設定] 視窗中,提供 ASPNETCORE_ENVIRONMENT 名稱的。In the Add/Edit application setting window, provide ASPNETCORE_ENVIRONMENT for the Name. 針對 [],提供環境(例如 Staging )。For Value, provide the environment (for example, Staging).
  5. 如果您想要在交換部署位置時,將環境設定維持在目前的位置,請選取 [部署位置設定] 核取方塊。Select the Deployment slot setting check box if you wish the environment setting to remain with the current slot when deployment slots are swapped. 如需詳細資訊,請參閱 Azure 檔中的在 Azure App Service 中設定預備環境For more information, see Set up staging environments in Azure App Service in the Azure documentation.
  6. 選取 [確定] 以關閉 [新增/編輯應用程式設定] 視窗。Select OK to close the Add/Edit application setting window.
  7. 選取 [設定] 分頁頂端的 [ 儲存]。Select Save at the top of the Configuration 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 部署:<EnvironmentName>將屬性包含在發行設定檔(. .pubxml)或專案檔中。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 distributions, use the export command at a command prompt for session-based variable settings and bash_profile file for machine-level environment settings.

在程式碼中設定環境Set the environment in code

UseEnvironment在建立主機時呼叫。Call UseEnvironment when building the host. 請參閱< ASP.NET Core Web 主機 >。See ASP.NET Core Web 主機.

取決於環境的組態Configuration by environment

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

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

將 IHostingEnvironment 插入 Startup.ConfiguInject IHostingEnvironment into Startup.Configure

插入 IHostingEnvironment Startup.ConfigureInject IHostingEnvironment into Startup.Configure. 當應用程式只需要 Startup.Configure 針對每個環境具有最低程式碼差異的幾個環境進行設定時,這個方法就很有用。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
    }
}

將 IHostingEnvironment 插入 Startup 類別Inject IHostingEnvironment into the Startup class

將插入 IHostingEnvironment 至此函式 Startup ,並將服務指派給欄位,以便在整個類別中使用 StartupInject IHostingEnvironment into the Startup constructor and assign the service to a field for use throughout the Startup class. 當應用程式需要針對少數環境設定啟動,但每個環境的程式碼差異最低時,這個方法會很有用。This approach is useful when the app requires configuring startup for only a few environments with minimal code differences per environment.

在下例中︰In the following example:

  • 環境會保留在欄位中 _envThe environment is held in the _env field.
  • _env會在和中使用 ConfigureServicesConfigure 以根據應用程式的環境來套用啟動設定。_env is used in ConfigureServices and Configure 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
        }
    }
}

Startup 類別慣例Startup class conventions

ASP.NET Core 應用程式啟動時,Startup 類別會啟動應用程式。When an ASP.NET Core app starts, the Startup class bootstraps the app. 應用程式可以 Startup 針對不同的環境定義個別的類別(例如, StartupDevelopment )。The app can define separate Startup classes for different environments (for example, StartupDevelopment). Startup 執行時間選取適當的類別。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. 當應用程式需要針對數個環境設定啟動,且每個環境有許多程式碼差異時,此方法很有用。This approach is useful when the app requires configuring startup for several environments with many code differences per environment.

若要實作以環境為基礎的 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>ServicesConfigure and ConfigureServices support environment-specific versions of the form Configure<EnvironmentName> and Configure<EnvironmentName>Services. 當應用程式需要針對數個環境設定啟動,且每個環境有許多程式碼差異時,此方法很有用。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();
    }
}

其他資源Additional resources