net core linux开发环境,在 ASP.NET Core 中使用多个环境

ASP.NET Core 基于使用环境变量的运行时环境配置应用行为。ASP.NET Core configures app behavior based on the runtime environment using an environment variable.

环境Environments

为了确定运行时环境,ASP.NET Core 从以下环境变量中读取信息:To determine the runtime environment, ASP.NET Core reads from the following environment variables:

ASPNETCORE_ENVIRONMENT(当调用 ConfigureWebHostDefaults 时)。ASPNETCORE_ENVIRONMENT when ConfigureWebHostDefaults is called. 默认 ASP.NET Core Web 应用模板调用 ConfigureWebHostDefaults。The default ASP.NET Core web app templates call ConfigureWebHostDefaults. ASPNETCORE_ENVIRONMENT 值替代 DOTNET_ENVIRONMENT。The 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:

Development:launchSettings.json 文件将本地计算机上的 ASPNETCORE_ENVIRONMENT 设置为 Development。Development : The launchSettings.json file sets ASPNETCORE_ENVIRONMENT to Development on the local machine.

Production:没有设置 DOTNET_ENVIRONMENT 和 ASPNETCORE_ENVIRONMENT 时的默认值。Production : The default if DOTNET_ENVIRONMENT and ASPNETCORE_ENVIRONMENT have not been set.

下面的代码:The following code:

当 ASPNETCORE_ENVIRONMENT 设置为 Development 时,调用 UseDeveloperExceptionPage。Calls UseDeveloperExceptionPage when ASPNETCORE_ENVIRONMENT is set to Development.

当 ASPNETCORE_ENVIRONMENT 的值设置为 Staging、Production 或 Staging_2 时,调用 UseExceptionHandler。Calls UseExceptionHandler when the value of ASPNETCORE_ENVIRONMENT is set to Staging, Production, or Staging_2.

将 IWebHostEnvironment 注入到 Startup.Configure 中。Injects 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();

});

}

The effective tag is: <environment include="Development">
The effective tag is: <environment exclude="Development">

The effective tag is:

<environment include="Staging,Development,Staging_2">

示例代码中的“关于”页包括前面的标记,并显示 IWebHostEnvironment.EnvironmentName 的值。The 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

本文档中使用的示例代码基于名为“EnvironmentsSample”的 Razor Pages 项目。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.jsonDevelopment 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.json 文件:The launchSettings.json file:

仅在本地开发计算机上使用。Is only used on the local development machine.

未部署。Is not deployed.

包含配置文件设置。contains profile settings.

下面的 JSON 显示名为“EnvironmentsSample”的 ASP.NET Core Web 项目的 launchSettings.json 文件,此项目是通过 Visual Studio 或 dotnet new 创建的: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"

}

}

}

}

前面的标记包含两个配置文件: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.

27a7a8e13cb8c7c50860e1dbb0c40a97.png

EnvironmentsSample:配置文件名称是项目名称。EnvironmentsSample: The profile name is the project name. 当使用 dotnet run 启动应用时,默认使用此配置文件。This 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.json 文件。The Visual Studio project properties Debug tab provides a GUI to edit the launchSettings.json file. 在 Web 服务器重新启动之前,对项目配置文件所做的更改可能不会生效。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.

74c588fd7a96ef6cdb218beeacc3bfac.png

以下 launchSettings.json 文件包含多个配置文件: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 命令,并将 --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. 下面的示例设置了多个主机配置值环境变量:

{

"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.json 文件仅由 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:

客户端资源被捆绑和缩小,并可能从 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.

设置环境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.EnvironmentName 的值。The About page from the sample code displays the value of IWebHostEnvironment.EnvironmentName.

Azure 应用服务Azure App Service

若要在 Azure 应用服务中设置环境,请执行以下步骤:To set the environment in Azure App Service, perform the following steps:

从“应用服务”边栏选项卡中选择应用。Select the app from the App Services blade.

在“设置”组中,选择“配置”边栏选项卡 。In the Settings group, select the Configuration blade.

在“应用程序设置”选项卡中,选择“新建应用程序设置”。In the Application settings tab, select New application setting.

在“添加/编辑应用程序设置”窗口中,在“名称”中提供 ASPNETCORE_ENVIRONMENT。In the Add/Edit application setting window, provide ASPNETCORE_ENVIRONMENT for the Name. 在“值”中提供环境(例如 Staging)。For Value, provide the environment (for example, Staging).

交换部署槽位时,如果希望环境设置保持当前槽位,请选中“部署槽位设置”复选框。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 应用服务中设置过渡环境。For more information, see Set up staging environments in Azure App Service in the Azure documentation.

选择“确定”以关闭“添加/编辑应用程序设置”窗口。Select OK to close the Add/Edit application setting window.

选择“配置”边栏选项卡顶部的“保存” 。Select Save at the top of the Configuration blade.

在 Azure 门户中添加、更改或删除应用设置后,Azure 应用服务自动重启应用。Azure App Service automatically restarts the app after an app setting is added, changed, or deleted in the Azure portal.

WindowsWindows

launchSettings.json 中的环境值替代在系统环境中设置的值。Environment values in launchSettings.json override values set in the system environment.

若要在使用 dotnet run 启动该应用时为当前会话设置 ASPNETCORE_ENVIRONMENT,则使用以下命令:To 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:

4b11210fd27f77f24b023aa35358e681.png

3fab7ad1f8c4e4c05b77a886ec0db1a7.png

打开管理命令提示符并运行 setx 命令,或打开管理 PowerShell 命令提示符并运行 [Environment]::SetEnvironmentVariable:Open 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.json 中的环境值替代在系统环境中设置的值。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 部署: 将 属性包含在发布配置文件 (.pubxml) 或项目文件中。For Windows IIS deployments: Include the property in the publish profile (.pubxml) or project file. 此方法在发布项目时设置 web.config 中的环境:This approach sets the environment in web.config when the project is published:

Development

每个 IIS 应用程序池Per IIS Application Pool

若要为在独立应用池中运行的应用设置 ASPNETCORE_ENVIRONMENT 环境变量(IIS 10.0 或更高版本支持此操作),请参阅环境变量 主题中的“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 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 stop was /y 和 net start w3svc。Execute 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

按环境配置Configuration by environment

To load configuration by environment, see ASP.NET Core 中的配置.

基于环境的 Startup 类和方法Environment-based Startup class and methods

将 IWebHostEnvironment 注入 Startup 类Inject IWebHostEnvironment into the Startup class

Inject 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:

环境保存在 _env 字段中。The environment is held in the _env field.

_env 在 ConfigureServices 和 Configure 中用于根据应用的环境应用启动配置。_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} 类和回退 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();

});

}

}

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

Configure 和 ConfigureServices 支持窗体 Configure 和 ConfigureServices 的环境特定版本。Configure and ConfigureServices support environment-specific versions of the form Configure and ConfigureServices. 当应用需要为多个环境(每个环境有许多代码差异)配置启动时,这种方法就非常有用: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值