第九节:ASP.NET Core 中多环境的使用

一. 环境相关配置

1. 说明

  ASP.NET Core 在应用启动时读取环境变量 ASPNETCORE_ENVIRONMENT, ASPNETCORE_ENVIRONMENT 可设置为任意值,但框架仅支持三个值:Development(开发)、Staging(测试)

和 Production(生产)。 如果未设置 ASPNETCORE_ENVIRONMENT,则默认为 Production(即生产环境)。

2. 获取方法

  IHostingEvironment对象,常用的四个方法分别是:

  ①:是否是开发 IsDevelopment 

  ②:是否是测试 IsStaging

  ③:是否是生产 IsProduction

  ④:是否是自定义的xxx环境 IsEnvironment("xxx")

详见:Startup类中的Configure方法

 

3. 环境变量配置的几种方法

 ①. cmd指令的形式设置: set ASPNETCORE_ENVIRONMENT=Staging

【仅对当前窗口有效,窗口关闭时,ASPNETCORE_ENVIRONMENT 设置将恢复为默认设置或计算机值。】

 ②. 电脑环境变量全局设置:我的电脑属性→环境变量→ASPNETCORE_ENVIRONMENT :Development

特别注意:以上两种方式,仅适用于通过命令启动的模式,如:dotnet ManyEnvironment.dll ,然后在浏览器中通过 5000端口进行访问。

 

 ③. 代码层次launchSettings.json中配置,配置文件中有两个选项,一个是IIS Express,一个是项目名称,这两个对应上面VS工具栏不同的启动方式,省略的话默认为 Production环境。

(代码层次的配置优先级要 大于 前面两种模式)

 

二. 基于环境的Startup 类和方法约定

1. Startup类约定

(1).说明

  Asp.Net Core启动时,可以为不同的环境单独定义 Startup{EnvironmentName 类(例如,StartupDevelopment、StartupProduction、StartupStaging),相应 Startup 类会在运行时得到选择。

优先考虑名称后缀与当前环境相匹配的类。 如果找不到匹配的 Startup{EnvironmentName},就会使用默认的 Startup 类。

(2).实战测试

  新建StartupDevelopment、StartupProduction、StartupStaging三个类,每个类中利用Run方法中止中间件并输出当前环境,然后在Program方法中利用反射获取Startup相关类,代码如下:

1  public static IWebHostBuilder CreateWebHostBuilder(string[] args)
2  {
3    //基于Startup类的加载方式
4    var assemblyName = typeof(Startup).GetTypeInfo().Assembly.FullName;
5    return WebHost.CreateDefaultBuilder(args).UseStartup(assemblyName);
6  }

然后在LaunchSetting.json中修改运行环境,发现加载的是不同的Startup,并输出对应的内容。

三个Startup代码分享

 1  public class StartupDevelopment
 2     {
 3         public StartupDevelopment(IConfiguration configuration)
 4         {
 5             Configuration = configuration;
 6         }
 7 
 8         public IConfiguration Configuration { get; }
 9 
10         public void ConfigureServices(IServiceCollection services)
11         {
12             services.Configure<CookiePolicyOptions>(options =>
13             {
14                 options.CheckConsentNeeded = context => true;
15                 options.MinimumSameSitePolicy = SameSiteMode.None;
16             });
17 
18 
19             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
20         }
21 
22         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
23         {
24             //终止中间件
25             app.Run(async context =>
26             {
27                 await context.Response.WriteAsync("Environment is Development");
28             });
29 
30             app.UseHttpsRedirection();
31             app.UseStaticFiles();
32             app.UseCookiePolicy();
33 
34             app.UseMvc(routes =>
35             {
36                 routes.MapRoute(
37                     name: "default",
38                     template: "{controller=Home}/{action=Index}/{id?}");
39             });
40         }
41     }
StartupDevelopment
 1   public class StartupProduction
 2     {
 3         public StartupProduction(IConfiguration configuration)
 4         {
 5             Configuration = configuration;
 6         }
 7 
 8         public IConfiguration Configuration { get; }
 9 
10         public void ConfigureServices(IServiceCollection services)
11         {
12             services.Configure<CookiePolicyOptions>(options =>
13             {
14                 options.CheckConsentNeeded = context => true;
15                 options.MinimumSameSitePolicy = SameSiteMode.None;
16             });
17 
18 
19             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
20         }
21 
22         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
23         {
24             //终止中间件
25             app.Run(async context =>
26             {
27                 await context.Response.WriteAsync("Environment is Production");
28             });
29 
30             app.UseHttpsRedirection();
31             app.UseStaticFiles();
32             app.UseCookiePolicy();
33 
34             app.UseMvc(routes =>
35             {
36                 routes.MapRoute(
37                     name: "default",
38                     template: "{controller=Home}/{action=Index}/{id?}");
39             });
40         }
41     }
StartupProduction
 1   public class StartupStaging
 2     {
 3         public StartupStaging(IConfiguration configuration)
 4         {
 5             Configuration = configuration;
 6         }
 7 
 8         public IConfiguration Configuration { get; }
 9 
10         public void ConfigureServices(IServiceCollection services)
11         {
12             services.Configure<CookiePolicyOptions>(options =>
13             {
14                 options.CheckConsentNeeded = context => true;
15                 options.MinimumSameSitePolicy = SameSiteMode.None;
16             });
17 
18 
19             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
20         }
21 
22         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
23         {
24             //终止中间件
25             app.Run(async context =>
26             {
27                 await context.Response.WriteAsync("Environment is Staging");
28             });
29 
30             app.UseHttpsRedirection();
31             app.UseStaticFiles();
32             app.UseCookiePolicy();
33 
34             app.UseMvc(routes =>
35             {
36                 routes.MapRoute(
37                     name: "default",
38                     template: "{controller=Home}/{action=Index}/{id?}");
39             });
40         }
41     }
StartupStaging

2. Startup方法约定

  把前面类约定中配置Program方法中恢复原样,然后在Startup类中新建:

    ConfigureStagingServices、ConfigureStaging

    ConfigureDevelopmentServices、ConfigureDevelopment

    ConfigureProductionServices、ConfigureProduction

  然后在LaunchSetting.json中修改运行环境,通过加断点的形式,发现进入到不同的Services中了。

 代码分享:

 1  public class Startup
 2     {
 3         public Startup(IConfiguration configuration)
 4         {
 5             Configuration = configuration;
 6         }
 7 
 8         public IConfiguration Configuration { get; }
 9 
10         /**************************************下面是Startup方法约定***********************************************/
11 
12         public void ConfigureStagingServices(IServiceCollection services)
13         {
14             services.Configure<CookiePolicyOptions>(options =>
15             {
16                 options.CheckConsentNeeded = context => true;
17                 options.MinimumSameSitePolicy = SameSiteMode.None;
18             });
19             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
20         }
21 
22         public void ConfigureStaging(IApplicationBuilder app, IHostingEnvironment env)
23         {
24             //终止中间件
25             app.Run(async context =>
26             {
27                 await context.Response.WriteAsync("Environment is Staging");
28             });
29         }
30 
31         public void ConfigureDevelopmentServices(IServiceCollection services)
32         {
33             services.Configure<CookiePolicyOptions>(options =>
34             {
35                 options.CheckConsentNeeded = context => true;
36                 options.MinimumSameSitePolicy = SameSiteMode.None;
37             });
38             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
39         }
40 
41         public void ConfigureDevelopment(IApplicationBuilder app, IHostingEnvironment env)
42         {
43             //终止中间件
44             app.Run(async context =>
45             {
46                 await context.Response.WriteAsync("Environment is Development");
47             });
48         }
49 
50 
51         public void ConfigureProductionServices(IServiceCollection services)
52         {
53             services.Configure<CookiePolicyOptions>(options =>
54             {
55                 options.CheckConsentNeeded = context => true;
56                 options.MinimumSameSitePolicy = SameSiteMode.None;
57             });
58             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
59         }
60 
61         public void ConfigureProduction(IApplicationBuilder app, IHostingEnvironment env)
62         {
63             //终止中间件
64             app.Run(async context =>
65             {
66                 await context.Response.WriteAsync("Environment is Production");
67             });
68         }
69 
70     }

 

 

 

 

 

!

  • 作       者 : Yaopengfei(姚鹏飞)
  • 博客地址 : http://www.cnblogs.com/yaopengfei/
  • 声     明1 : 本人才疏学浅,用郭德纲的话说“我是一个小学生”,如有错误,欢迎讨论,请勿谩骂^_^。
  • 声     明2 : 原创博客请在转载时保留原文链接或在文章开头加上本人博客地址,否则保留追究法律责任的权利。
 
posted @ 2019-05-22 10:05  Yaopengfei  阅读(1347)  评论(1编辑  收藏  举报